In Kotlin, you may define and use the lambda and anonymous function, which is called “function literals”.
The ‘function literal’ is the function that is not declared and passed immediately as an expression.
How to define lambda function?
The lambda expression is always surrounded by curly braces as shown below:
You may also write lambda function like this:
A few things to note about the lambda function in Kotlin:
- You may declare the parameters in full syntactic form inside the curly braces.
- The parameters can optionally have type annotations.
- The body of the function is given after the –> sign.
- The return value of the function is the last expression inside the lambda body if the return type of the lambda is not Unit.
Now, let us look at a few examples of using the Kotlin lambda functions.
Display a message using a lambda function example
In this example, we will display a message using the lambda function:
fun main(args: Array<String>) { val msg = { println("Kotlin Lambda Tutorial!")} msg() }
The output:
An example of the lambda function with parameters
In this example, we will get the sum of two parameters in the lambda function. The sum is displayed as follows:
fun main(args: Array<String>) { val sum = { a: Int, b: Int -> a + b } println(sum(10,20)) }
The result:
Leaving the optional annotations example
The same can be achieved as in the above example without using the optional annotations. So, the code looks like this:
fun main(args: Array<String>) { val sum: (Int, Int) -> Int = { a, b -> a + b } println(sum(50,50)) }
The output:
The example of the lambda return value
As mentioned in the introductory part, the return value of the lambda is the last expression if the return type is not Unit.
The example below uses when expression to demonstrate that:
fun main(args: Array<String>) { val retDemo = { grade : Int -> when(grade) { in 1..10 -> "The value is between 1 to 10" in 11..20 -> "The value is between 11 to 20" in 21..30 -> "Between 21 to 30" in 31..40 -> "Between 31 to 40" else -> "Above 40" } } print(retDemo(19)) }
The output of the above code: