Following code tries to break out from forEach lambda when ascii value of character is 59. It however does not compile.
fun foo() {
run label@ {
"abcd".chars().forEach {
if (it == 59) return@label
print(it)
}
print("completed forEach")
}
}
However, it compiles if forEach is used directly on characters instead of calling chars() method to get ascii values as shown below
fun foo() {
run label@ {
"abcd".forEach {
if (it == 'd') return@label
print(it)
}
print("completed forEach")
}
}
CodePudding user response:
It’s because chars() returns an IntStream, which is not an Iterable so the Kotlin inline function Iterable.forEach is not available. You’re calling a Java function named forEach that is not inline. You can only break out of lambdas that are passed to inline functions and whose functional parameter is not marked crossinline.
CodePudding user response:
Following change worked
"abcd".chars().toArray().forEach {...}
