gpt4 book ai didi

Kotlin 内联函数只有一个 return 语句

转载 作者:行者123 更新时间:2023-12-02 12:44:07 25 4
gpt4 key购买 nike

我想使用内联函数返回函数外(跳过打印“之后”)。所以当我使用

inline fun test() {
return
}

fun test1() {
println("before")
test()
println("after")
}
test1()
输出是
before  
after
当我使用
inline fun test(callBack: () -> Unit) {
callBack()
}

fun test1() {
println("before")
test {
return
}
println("after")
}
test1()
输出是
before
所以我想知道为什么第一个内联函数中的 return 语句不起作用。为什么第一段代码不起作用?

最佳答案

根据文档:

(return) by default returns from the nearest enclosing function or anonymous function. -- returns-and-jumps


A return statement without a label always returns from the function declared with the fun keyword. -- anonymous-functions


实际上我会回答这个问题:为什么它在第二个例子中起作用?答案是:

In Kotlin, we can only use a normal, unqualified return to exit a named function or an anonymous function. This means that to exit a lambda, we have to use a label, and a bare return is forbidden inside a lambda, because a lambda cannot make the enclosing function return (...). But if the function the lambda is passed to is inlined, the return can be inlined as well, so it is allowed.-- non local returns

关于Kotlin 内联函数只有一个 return 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64084936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com