August 2017
Intermediate to advanced
440 pages
10h
English
Functions with function parameters might act similarly to native structures (such as loops). We've already seen the ifSupportsLolipop function and the repeatUntilError function. An even more common example is the forEach modifier. It is an alternative to the for control structure, and it calls a parameter function with each element one after another. This is how it could be implemented (there is a forEach modifier in the Kotlin standard library, but we will look at it later because it includes elements that have not yet been presented):
fun forEach(list: List<Int>, body: (Int) -> Unit) {
for (i in list) body(i)
}
// Usage
val list = listOf(1, 2, 3, 4, 5)
forEach(list) { print(it) } // Prints: 12345
The big problem is that ...
Read now
Unlock full access