-
Notifications
You must be signed in to change notification settings - Fork 22
Lamda Expression
Devrath edited this page Feb 1, 2024
·
6 revisions
Both are equal Normal function
fun addTwoNum(x : Int , y :Int) : Int {
return x+y
}
Using lamda expression: It is a function without a name
{x,y -> x+y }
val printName = { println("Welcome to our world") }
printName()
printName.invoke()
val lamda : (DataType1,DataType2) -> ReturnType = { variable1:DataType1, variable2:DataType2 -> methodBody }
Type:1
val lamda = { a:Int , b:Int -> a+b }
Type:2
val lamda : (Int,Int) -> Int = { a,b -> a+b }
// 1- With Parameters and Return Value
fun type1() {
val add1:(Int,Int) -> Int = { a:Int , b:Int -> a+b }
println(add1(1,2))
}
// 2- With Parameters and no return value
fun type2() {
val add2 : (Int,Int) -> Unit = { a,b -> println(a+b) }
add2(1,2)
}
// 3- No Parameters but with return value
fun type3() {
val add3 : () -> String = { "Hello world" }
println(add3())
}
// 4- No Parameters and no return value
fun type4() {
val add4 : () -> Unit = { println("Hello World") }
add4.invoke()
}