我不太明白這里發生了什么
fun foo() {
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return // non-local return directly to the caller of foo()
print(it)
}
println("this point is unreachable")
}
fun main() {
foo()
}
輸出是
12
所以整數1和2。那是因為 with1和2運算式的if (it == 3)計算結果為false. 但是return在這里做什么?回傳什么?去哪里?有沒有辦法把這個寫得更冗長?
uj5u.com熱心網友回復:
您的函式foo()回傳一個隱式單位,因此當您呼叫 時return,它只是foo()立即回傳隱式單位。
您可以更詳細地撰寫return Unit,并且可以使用常規for回圈。這基本上與forEach.
fun foo(): Unit {
for (it in listOf(1, 2, 3, 4, 5)) {
if (it == 3) return Unit
print(it)
}
println("this point is unreachable")
}
相反,如果您使用return@forEach, 有或沒有隱式 Unit,它將從 lambda 回傳,這與continue在傳統的 for 回圈中使用相同,因為forEachlambda 被重復呼叫,每次回圈迭代一次。
如果foo()回傳 Unit 以外的東西,則必須回傳該型別才能執行非本地回傳:
fun foo(): Boolean {
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return false
print(it)
}
println("this point is unreachable")
return true
}
您只能從不是crossinline.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/535153.html
標籤:科特林
下一篇:區分函式和擴展
