Lambdas Expressions in Kotlin
package com.example.my_kotlin_practice
fun main(args: Array<String>) {
// Kotlin lambda is a function which has no name and defined with a curly braces {} which takes zero or more parameters and
// body of function.
// The body of function is written after variable (if any) followed by -> operator.
// Syntax : {variable with type -> body of the function}
val upperCase = { str:String -> str.uppercase() }
println(upperCase("hello world!"))
var lambdaFunction1 = {a:Int,b:Int->a+b}
println(lambdaFunction1(2,3))
var lambdaFunction2 = {msg:String->
println("Hello World")
println("Message is $msg")
}
lambdaFunction2("Hello")
var lambdaMinus:(Int,Int)-> Int = {x,y->x-y}
var unitLambda = {msg: String->println(msg)}
var squareLambda:(Int)->Int = {it -> it*it}
println("Square is : ${squareLambda(9)}")
arithmeticOpr(10,20) { x, y -> x + y }
arithmeticOpr(10,20) { x, y -> x - y }
arithmeticOpr(10,20) { x, y -> x * y }
arithmeticOpr(10,20) { x, y -> x / y }
}
fun arithmeticOpr(a:Int,b:Int,fn:(Int,Int)-> Int){
var result = fn(a,b)
println("Result is : $result")
}
OUTPUT :
HELLO WORLD! 5 Hello World Message is Hello Square is : 81 Result is : 30 Result is : -10 Result is : 200 Result is : 0 Process finished with exit code 0
Comments
Post a Comment