Learning Kotlin: it is a thing

Submitted by Robert MacLean on Mon, 07/09/2018 - 09:00

More Information

  • This is the 15th post in a multipart series.
    If you want to read more, see our series index

Our last post covered a lot of the awesome extensions to collections in Kotlin and as someone who comes from .NET and Java I think about writing Lambdas in a specific way.

  1.  val numbers = listOf(1,5,6,8,10)
  2. val evens = numbers.filter({ num -> num % 2 == 0 })
  3. println(evens)

In .NET/Java we need a range variable, in the example above it is num which refers to the item in the collection we are working on. Kotlin knows you will always have a range variable, so why not simplify it and make it have a common name it:

  1.  val numbers = listOf(1,5,6,8,10)
  2.  val evens = numbers.filter({ it % 2 == 0 })
  3.  println(evens)

Here we got ride of the num -> start of the lambda and we can just refer to the automatically created range variable it.