Lambda expression in kotlin is an anonymous(a function without name)function. Lambda
Expressions help us to write a function in a short way. We can pass functions as arguments to methods and return them. Lambdas are one of the most powerful features in Kotlin. It allows modeling functions in a much simpler way.
Let’s define a lambda expression to see the basic syntax.
To define a lambda, we need to give a name, define a type, pass argument and return body:
Lambda expression syntax
val lambdaName : Type = { argumentList -> codeBody }
Let's create a simple lambda expression for prints www.developerlibs.com.
Example -1
val printDomain = {
println("www.developerlibs.com")
}
//We can invoke the above by using the following syntax.
printDomain()
// or
printDomain.invoke()
Lambda with parameters and return type
We can create a lambda expression that takes parameters. We use the syntax:
Example - 2
val sayHello = { text: String ->
println("Hello, $text!")
}
sayHello("kotlin")
// or with multiple parameters
val printSummary = { text: String, score: Int ->
println("Kotlin '$text' get $score points.")
}
printSummary("kotlin", 123)
Anonymous Functions
We’ve seen that lambda expressions can’t explicitly specify a return type as illustrated below.
var mul = { a: Int, b: Int -> a * b }
var result = mul(2,3) //result is an int 6
In order to set the return types explicitly, we can use Anonymous functions. An anonymous function doesn’t require a name.
fun main(args: Array<String>) {
//Defining
val annoMul = fun(x: Int, y: Int): Int = x * y
//Invoking
print(annoMul(2,3)) //6
}
If the parameter and return type of the anonymous function isn’t defined, it can be inferred just like normal functions.
Let’s use Anonymous functions inside standard library high order functions.
var myList = listOf<Int>(1,2,5,7,6,10)
myList = myList.filter(fun(item) = (item%2 ==0) )
println(myList)
filter is a higher order function that checks the given condition over each of the list items.