On the other hand, return statement inside a lambda function, that was passed to an inline function, exits the enclosing outer function. The lambda is inlined, so the return inside it is actually treated as a return from outer function scope.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun f1() { | |
// Anonymous function: this will print 1 2, return acts like a break. | |
listOf(1,2).forEach(fun(it: Int): Unit { | |
println(it) | |
return | |
}) | |
} | |
fun f2() { | |
// Lambda function: this will only print 1, return actually exits | |
// from the outer function f2(). As forEach() is an inline function, the lambda, | |
// that is passed to it as an argument becomes inlined. | |
listOf(1,2).forEach { | |
println(it) | |
return | |
} | |
} |
No comments :
Post a Comment