August 2017
Intermediate to advanced
440 pages
10h
English
Let's look at a case in which we need to return from a lambda expression and not from a function. We can do this using labels. Here is an example of a return from a lambda expression using labels:
inline fun <T> forEach(list: List<T>, body: (T) -> Unit) { // 1
for (i in list) body(i)
}
fun printMessageButNotError(messages: List<String>) {
forEach(messages) messageProcessor@ { // 2
if (it == "ERROR") return@messageProcessor // 3
print(it)
}
}
// Usage
val list = listOf("A", "ERROR", "B", "ERROR", "C")
processMessageButNotError(list) // Prints: ABC
Read now
Unlock full access