Kotlin Tutorial · Functional Kotlin and Collections · Lesson 18 of 31
Kotlin Lambdas and Higher-Order Functions
Function types, lambdas, the it parameter, trailing lambdas, function references and closures.
Lambdas and function types
A lambda is a function literal in braces: { a: Int, b: Int -> a + b }. Its type is written
(Int, Int) -> Int. A lambda with one parameter can use the implicit name it.
fun main() {
val add: (Int, Int) -> Int = { a, b -> a + b }
val shout = { text: String -> text.uppercase() + "!" }
val double: (Int) -> Int = { it * 2 }
println(add(2, 3))
println(shout("hello"))
println(double(21))
}
Output
5 HELLO! 42
Run this on your computer — see “Get Started” for setup.
Higher-order functions
A higher-order function takes or returns a function. When the last parameter is a function, the lambda goes
after the parentheses (a trailing lambda), which is why Kotlin code reads like list.filter { ... }.
::name is a function reference. Lambdas can read and change variables from the enclosing scope.
fun retry(times: Int, action: (attempt: Int) -> Boolean): Boolean {
for (attempt in 1..times) {
if (action(attempt)) return true
}
return false
}
fun isValidEmail(s: String) = "@" in s
fun main() {
var calls = 0 // captured and changed by the lambda
val ok = retry(3) { attempt ->
calls++
println("attempt $attempt")
attempt == 2
}
println("ok=$ok after $calls calls")
println(listOf("[email protected]", "nope").filter(::isValidEmail))
}
Output
attempt 1 attempt 2 ok=true after 2 calls [[email protected]]
Run this on your computer — see “Get Started” for setup.
Test yourself
In items.map { it * 2 }, what is it?
A keyword for the listThe implicit name of the lambda's single parameterThe indexThe return value
Show answer
Answer: The implicit name of the lambda's single parameter