Kotlin | Lambdas Expressions and Anonymous Functions

09 May, 2022
In this article, we are going to learn lambdas expression and anonymous function in Kotlin. While syntactically similar, Kotlin and Java lambdas have very different features. 
Lambdas expression and Anonymous function both are function literals means these functions are not declared but passed immediately as an expression. 
As we know, syntax of Kotlin lambdas is similar to Java Lambdas. A function without name is called anonymous function. For lambda expression we can say that it is anonymous function.
Example: 
Kotlin
fun main(args: Array<String>) {    val company = { println("GeeksforGeeks")}     // invoking function method1    company()      // invoking function method2    company.invoke()}
Output: 
GeeksforGeeks
GeeksforGeeks
Syntax of Lambda expression – 
val lambda_name : Data_type = { argument_List -> code_body }
A lambda expression is always surrounded by curly braces, argument declarations go inside curly braces and have optional type annotations, the code_body goes after an arrow -> sign. If the inferred return type of the lambda is not Unit, then the last expression inside the lambda body is treated as return value.
Example: 
val sum = {a: Int , b: Int -> a + b}
In Kotlin, the lambda expression contains optional part except code_body. Below is the lambda expression after eliminating the optional part. 
val sum:(Int,Int) -> Int = { a, b -> a + b}
Note: We don’t always require a variable because it can be passed directly as an argument to a function.
Kotlin program of using lambda expression-  
Kotlin
// with type annotation in lambda expressionval sum1 = { a: Int, b: Int -> a + b } // without type annotation in lambda expressionval sum2:(Int,Int)-> Int  = { a , b -> a + b} fun main(args: Array<String>) {    val result1 = sum1(2,3)    val result2 = sum2(3,4)    println("The sum of two numbers is: $result1")    println("The sum of two numbers is: $result2")     // directly print the return value of lambda    // without storing in a variable.    println(sum1(5,7))}
Output: 
The sum of two numbers is: 5
The sum of two numbers is: 7
12
Kotlin’s type inference helps the compiler to evaluate the type of a lambda expression. Below is the lambda expression using which we can compute the sum of two integers.  
val sum = {a: Int , b: Int -> a + b}
Here, Kotlin compiler self evaluate it as a function which take two parameters of type Int and returns Int value. 
(Int,Int) -> Int
If we wanted to return String value than we can do it with help of toString() inbuilt function. 
Kotlin
val sum1 = { a: Int, b: Int ->    val num = a + b    num.toString()     //convert Integer to String}fun main(args: Array<String>) {    val result1 = sum1(2,3)    println("The sum of two numbers is: $result1")}
Output: 
The sum of two numbers is: 5
In above program, Kotlin compiler self evaluate it as a function which takes two integer values and returns String. 
(Int,Int) -> String  
We must explicitly declare the type of our lambda expression. If lambda returns no value then we can use: Unit Pattern: (Input) -> Output
Lambdas examples with return type –  
val lambda1: (Int) -> Int = (a -> a * a)
val lambda2: (String,String) -> String = { a , b -> a + b }
val lambda3: (Int)-> Unit = {print(Int)}
Lambdas can be used as class extension:  
val lambda4: String.(Int) -> String = {this + it} 
Here, it represents the implicit name of single parameter and we will discuss later.
Kotlin program when lambdas used as class extension –  
Kotlin
val lambda4 : String.(Int) -> String = { this + it } fun main(args: Array<String>) {    val result = "Geeks".lambda4(50)    print(result)}
Output: 
Geeks50
Explanation: In the above example, we are using the lambda expression as class extension. We have passed the parameters according to the format given above. this keyword is used for the string and it keyword is used for the Int parameter passed in the lambda. Then the code_body concatenates both the values and returns to variable result. 
In most of cases lambdas contains the single parameter. Here, it is used to represent the single parameter we pass to lambda expression.
Kotlin program using shorthand form of lambda function –  
Kotlin
val numbers = arrayOf(1,-2,3,-4,5) fun main(args: Array<String>) {      println(numbers.filter {  it > 0 })}
Output: 
[1, 3, 5]
Kotlin program using longhand form of lambda function – 
Kotlin
val numbers = arrayOf(1,-2,3,-4,5) fun main(args: Array<String>) {     println(numbers.filter {item -> item > 0 })}
Output: 
[1, 3, 5] 
After execution of lambda the final value returned by the lambda expression. Any of these Integer, String or Boolean value can be returned by the lambda function.
Kotlin program to return String value by lambda function –  
Kotlin
val find =fun(num: Int): String{if(num % 2==0 && num < 0) {    return "Number is even and negative"   }    else if (num %2 ==0 && num >0){    return "Number is even and positive"    }    else if(num %2 !=0 && num < 0){    return "Number is odd and negative"    }    else {    return "Number is odd and positive"    }}fun main(args: Array<String>) {    val result = find(112)    println(result)}
Output: 
Number is even and positive
An anonymous function is very similar to regular function except for the name of the function which is omitted from the declaration. The body of the anonymous function can be either an expression or block.
Example 1: Function body as an expression  
fun(a: Int, b: Int) : Int = a * b
Example 2: Function body as a block 
fun(a: Int, b: Int): Int {
    val mul = a * b
    return mul
}
Return type and parameters- 
The return type and parameters are also specified in same way as for regular function but we can omit the parameters if they can be inferred from the context.The return type of the function can be inferred automatically from the function if it is an expression and has to be specified explicitly for the anonymous function if it is body block.
The return type and parameters are also specified in same way as for regular function but we can omit the parameters if they can be inferred from the context.
The return type of the function can be inferred automatically from the function if it is an expression and has to be specified explicitly for the anonymous function if it is body block.
Difference between lambda expressions and anonymous functions-The only difference is the behavior of non-local returns. A return statement without a label always returns from the function declared with the fun keyword. This means that a return inside a lambda expression will return from the enclosing function, whereas a return inside an anonymous function will return from the anonymous function itself.
Kotlin program to call the anonymous function-  
Kotlin
// anonymous function with body as an expressionval anonymous1 = fun(x: Int, y: Int): Int = x + y // anonymous function with body as a blockval anonymous2 = fun(a: Int, b: Int): Int {            val mul = a * b            return mul            }fun main(args: Array<String>) {    //invoking functions    val sum = anonymous1(3,5)    val mul = anonymous2(3,5)    println("The sum of two numbers is: $sum")    println("The multiply of two numbers is: $mul")}
Output: 
The sum of two numbers is: 8
The multiply of two numbers is: 15
 
kevilpy
anikakapoor
rajeev0719singh
ubedk
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.