Learning Kotlin: Lambdas
Note *
- This is the 5th post in a multipart series. If you want to read more, see our series index.
So, following C#, Kotlin has lambda support, with the change of => becoming ->. The koan starts with some nice examples at the start:
fun example() {
val sum = { x: Int, y: Int -> x + y }
val square: (Int) -> Int = { x -> x * x }
sum(1, square(2)) == 5
}
Basically, though, the code that needs to be done is to check a collection if all items are even—which can easily be done with:
fun task4(collection: Collection<Int>): Boolean = collection.all { item -> item % 2 == 0 }