January 2018
Intermediate to advanced
414 pages
10h 29m
English
Considering that we just use a range of numbers that we cycle in a loop:
fun printNumbers(){ val range = 1..10 for(i in range){ println(i) }}
We could use a lambda to access them:
fun printNumbers(){ val range = 1..10 range.forEach { i -> println(i) }}
But lambda could be easily shortened with the inferred it object:
fun printNumbers(){ val range = 1..10 range.forEach { println(it) }}
And we don't really need a variable for it, so we could simplify it with:
fun printNumbers() { (1..10).forEach { println(it) }}
But since we just print the elements of forEach, we could just use a method reference instead of the lambda:
fun printNumbers() { (1..10).forEach(::println)}
Read now
Unlock full access