Kotlin - 尝试从 lambda 返回封闭函数时出现“此处不允许返回”错误

dak*_*aka 3 kotlin

foo尝试从 lambda返回封闭函数 ( ) 会显示错误return is not allowed here

这里发生了什么事?难道我做错了什么?

fun bar( baz: () -> Unit ) {

    // Empty function
}

fun foo() : Unit? {

    return null // this works fine

    bar {

        return null // shows error 'return is not allowed here'
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

我也尝试过:

...

bar {

    return@bar null
}

...
Run Code Online (Sandbox Code Playgroud)

但这给出了错误Null can not be a value of a non-null type Unit

Eug*_*nko 6

在 Kotlin 中有一条规则——总是return返回fun。可以使用return@<label/function name>从函数或 lambda 表达式返回。

接下来,来了inline fun。内联函数不是真正的函数,它们被内联到调用站点中,因此,可以从作为此类函数参数的 lambda 内部返回(标准库中有很多这样的示例)

总结一下:

inline fun bar(a: () -> Unit) { a() }
fun buz() : Int {
  bar { return 42 } /// such return is only possible to inline fun
  return 10
}
val x = buz() /// will be 42
Run Code Online (Sandbox Code Playgroud)
bar { if (something) return@bar }
Run Code Online (Sandbox Code Playgroud)

这里我们从 lambda 返回,而不是从函数返回。