Main navigation

Learning Kotlin: it is a thing

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.

val numbers = listOf(1,5,6,8,10)

val evens = numbers.filter({ num -> num %2==0})

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:

val numbers = listOf(1,5,6,8,10)

val evens = numbers.filter({ it %2==0})

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.