Skip to content

Lamda Expression

Devrath edited this page Feb 1, 2024 · 6 revisions

Comparing two ways of writing a function

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 }

There are 2 ways of executing a lamda

val printName = { println("Welcome to our world") }
printName()
printName.invoke()

Syntax of lamda expression

val lamda : (DataType1,DataType2) -> ReturnType = { variable1:DataType1, variable2:DataType2 -> methodBody  }
Screenshot 2024-02-01 at 3 16 53β€―PM

Type:1

val lamda = { a:Int , b:Int -> a+b }

Type:2

val lamda : (Int,Int) -> Int = { a,b -> a+b }

Types of lamda expressions

    // 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()
    }
Clone this wiki locally