Learning Kotlin: it is a thing
Note * 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. 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’s num—which refers to the item in the collection we’re working on. Kotlin knows you’ll always have a range variable, so why not simplify it and make it use a common name, it?
val numbers = listOf(1, 5, 6, 8, 10)
val evens = numbers.filter({ it % 2 == 0 })
println(evens)
Here, we’ve removed the num -> at the start of the lambda, and we can simply refer to the automatically created range variable it.