June 2018
Intermediate to advanced
310 pages
6h 32m
English
Another common task is filtering a collection. You know the drill. You iterate over it and put only values that fit your criteria in a new collection. For example, if given a range of numbers between 1-10, we would like to return only odd ones. Of course, we've already learned this lesson from the previous example, and wouldn't simply create a function called filterOdd(), as later we would be required to also implement filterEven(), filterPrime(), and so on. We'll receive a lambda as the second argument right away:
fun filter(numbers: List<Int>, check: (Int)->Boolean): MutableList<Int> { val result = mutableListOf<Int>() for (n in numbers) { if (check(n)) { result.add(n) } } return result}
Invoking it will print only odd numbers. ...
Read now
Unlock full access