Industrial Training




Kotlin Lambda Function


Lambda is a function which has no name. Lambda is defined with a curly braces {} which takes variable as a parameter (if any) and body of function. The body of function is written after variable (if any) followed by -> operator.

Syntax of lambda


{ variable -> body_of_function}  
{ variable -> body_of_function}  

Before we talk about lambda, let's see a simple example of addition of two numbers using normal function.


Normal function: addition of two numbers


In this example, we create a function addNumber() passing two arguments (a,b) calling from the main function.


fun main(args: Array< String>){  
    addNumber(5,10)  
}  
fun addNumber(a: Int, b: Int){  
    val add = a + b  
    println(add)  
}  
fun main(args: Array< String>){  
    addNumber(5,10)  
}  
fun addNumber(a: Int, b: Int){  
    val add = a + b  
    println(add)  
}  			  
Output:
15

Lambda function: addition of two numbers


The above program will be rewritten using lambda function as follow:


fun main(args: Array< String>){  
    val myLambda: (Int) -> Unit= {s: Int -> println(s) } //lambda function  
    addNumber(5,10,myLambda)  
}  
fun addNumber(a: Int, b: Int, mylambda: (Int) -> Unit ){   //high level function lambda as parameter  
    val add = a + b  
    mylambda(add) // println(add)  
}  
fun main(args: Array< String>){  
    val myLambda: (Int) -> Unit= {s: Int -> println(s) } //lambda function  
    addNumber(5,10,myLambda)  
}  
fun addNumber(a: Int, b: Int, mylambda: (Int) -> Unit ){   //high level function lambda as parameter  
    val add = a + b  
    mylambda(add) // println(add)  
}  

Output:
15

In the above program we create a lambda expression {s: Int -> println(s) } with its return type Unit. The lambda function is padded as an parameter in high level function addNumber(5,10,myLambda). The variable mylambda in function definition is actually a lambda function. The functionality (body) of mylambda is already given in lambda function.



Hi I am Pluto.