Lambda expressions
Kotlin allows you to write even more concise code for functions by using lambda expressions.
For example, the following uppercaseString() function:
fun uppercaseString(text: String): String {
return text.uppercase()
}
fun main() {
println(uppercaseString("hello"))
// HELLO
}Can also be written as a lambda expression:
fun main() {
val upperCaseString = { text: String -> text.uppercase() }
println(upperCaseString("hello"))
// HELLO
}Pass to another function
A great example of when it is useful to pass a lambda expression to a function, is using the .filter() function on collections:
fun main() {
val numbers = listOf(1, -2, 3, -4, 5, -6)
val positives = numbers.filter ({ x -> x > 0 })
val isNegative = { x: Int -> x < 0 }
val negatives = numbers.filter(isNegative)
println(positives)
// [1, 3, 5]
println(negatives)
// [-2, -4, -6]
}Info
If a lambda expression is the only function parameter, you can drop the function parentheses
():val positives = numbers.filter { x -> x > 0 }This is an example of a trailing lambda, which is discussed in more detail at the end of this chapter.