return标签

return允许我们从外层函数返回,最重要的使用场景莫过于从lambda表达式返回。

fun foo() {
    val list = listOf(1, 2, 4, 5, 7, 10, 0, 11)
    list .forEach {
        if (it == 0) return
            print(it)
        }
}
// 1, 2, 4, 5, 7, 10

以上return语句会从最近一层函数返回,另外需要注意的是这种非本地的返回仅仅在lambda表达式被传递给inline函数时才支持,如果你想返回lambda表达式,那么你需要使用标签

fun foo() {
    val list = listOf(1, 2, 4, 5, 7, 10, 0, 11)
    list.forEach lit@ {
        if (it == 0) return@lit
        print(it)
    }
}
// 1, 2, 4, 5, 7, 10, 11

请着重理解上述区别。

在上述的标签返回中,更多的时候我们使用隐式的标签:比如与传入lambda表达式的函数名一致的标签。

fun foo1() {
    val list = listOf(1, 2, 4, 5, 7, 10, 0, 11)
    list.forEach {
        if (it == 0) return@forEach
        print(it)
    }
}

我们也可以使用匿名函数来实现上述功能,此时return仅仅是返回匿名函数本身。

fun foo() {
    val list = listOf(1, 2, 4, 5, 7, 10, 0, 11)
    list.forEach(fun(value: Int) {
        if (value == 0) return
        print(it)
    })
}
// 1, 2, 4, 5, 7, 10, 11

当需要返回一个值时:

return@a 1

意味着在变迁@a处返回1而不是在标签(@a 1)处返回。

results matching ""

    No results matching ""