Learning Kotlin: Lambdas

Submitted by Robert MacLean on Tue, 06/19/2018 - 09:00

More Information

So following C#, Kotlin has Lambda support with the change if => becoming -> and the Koan starts with some nice examples at the start:

  1. fun example() {
  2.  
  3.     val sum = { x: Int, y: Int -> x + y }
  4.     val square: (Int) -> Int = { x -> x * x }
  5.  
  6.     sum(1, square(2)) == 5
  7. }

Basically, though, the code that needs to be done is to check a collection if all items are even, which is easily done with:

  1. fun task4(collection: Collection<Int>): Boolean = collection.any({item -> item % 2 == 0})