Kotlin Lambda Function

A lambda function is a function that does not need to declare, but we can pass it immediately as an expression. This is an anonymous function which is usually created during a function call to act as a function parameter.

Syntax of Lambda Function
val sum = { a: Int, b: Int -> a + b}

The lambda function is surrounded by curly braces, parameter declaration and the body are wrapped inside the curly braces. The body goes after an -> sign. If the return type of lambda function is not unit, the last expression in the function treats like a return type.

Example of Lambda Function
fun main(args : Array<String>)  {  
    val a = 100
    val b = 200
    val sum: (Int) -> Unit = { c: Int -> println(c)} // lambda function
    lambdaFunc(a,b,sum)
}
fun lambdaFunc(x: Int,y: Int,sum: (Int) -> Unit) {
    val add = x+y
    sum(add)
}
Output of Lambda Function
300






Read more articles


General Knowledge



Learn Popular Language