5 - Lambdas Expressions and Anonymous Functions
5 - Lambdas Expressions and Anonymous Functions
Lambdas expression and Anonymous function both are function literals means
these functions are not declared but passed immediately as an expression.
Lambda Expression –
Example:
Kotlin
Output:
GeeksforGeeks
GeeksforGeeks
Example:
Kotlin
Output:
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.
Kotlin
Output:
In above program, Kotlin compiler self evaluate it as a function which takes two
integer values and returns String.
Here, it represents the implicit name of single parameter and we will discuss
later.
Kotlin
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.
Kotlin
Output:
[1, 3, 5]
Kotlin
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
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:
Anonymous Function
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.
1. 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.
2. 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.
Kotlin
Output: