使用 return@label 从 lambda 中脱离出来,在 Kotlin 中对 "string".chars() 不起作用
Breaking out from lambda using return@label not working in Kotlin for "string".chars()
当字符的 ascii 值为 59 时,以下代码尝试从 forEach
lambda 跳出。但是 无法编译 。
fun foo() {
run label@ {
"abcd".chars().forEach {
if (it == 59) return@label
print(it)
}
print("completed forEach")
}
}
但是,如果直接在字符上使用 forEach 而不是调用 chars()
方法来获取 ascii 值,它 编译 如下所示
fun foo() {
run label@ {
"abcd".forEach {
if (it == 'd') return@label
print(it)
}
print("completed forEach")
}
}
因为 chars()
returns IntStream 不是 Iterable 所以 Kotlin 内联函数 Iterable.forEach
不可用。您正在调用一个名为 forEach
的 Java 函数,该函数不是内联的。您只能突破传递给内联函数且其功能参数未标记 crossinline
.
的 lambda
以下更改有效
"abcd".chars().toArray().forEach {...}
当字符的 ascii 值为 59 时,以下代码尝试从 forEach
lambda 跳出。但是 无法编译 。
fun foo() {
run label@ {
"abcd".chars().forEach {
if (it == 59) return@label
print(it)
}
print("completed forEach")
}
}
但是,如果直接在字符上使用 forEach 而不是调用 chars()
方法来获取 ascii 值,它 编译 如下所示
fun foo() {
run label@ {
"abcd".forEach {
if (it == 'd') return@label
print(it)
}
print("completed forEach")
}
}
因为 chars()
returns IntStream 不是 Iterable 所以 Kotlin 内联函数 Iterable.forEach
不可用。您正在调用一个名为 forEach
的 Java 函数,该函数不是内联的。您只能突破传递给内联函数且其功能参数未标记 crossinline
.
以下更改有效
"abcd".chars().toArray().forEach {...}