如何从Kotlin的匿名lambda返回?

时间:2020-10-26 13:35:26

标签: kotlin lambda

如何从Kotlin的匿名lambda返回?

以某种方式,编译器不允许在lambda主体内部返回。由于lambda是匿名用户,因此return@...在这里是不可能的。

class Foo {

    var function: (String) -> Unit = { _ -> }

    init {
        function = { text ->

            if (text == "foo"){
                // do side effects here
                return
                //'return' is not allowed here
                //This function must return a value of type Foo
            }
            // do side other side effects
        }
    }
}

编辑:更新示例,因此很明显,此问题与return语句有关,而不与编码实践有关

2 个答案:

答案 0 :(得分:3)

使用标签:

class Foo {

    var function: (String) -> Unit

    init {
        function = function@ { text ->
    
            if (text == "foo"){
                return@function
            }

            print(text)

        }
    }
}

答案 1 :(得分:1)

尽管有可能做到,但我并不喜欢这种事情,而是在实际可行时更喜欢重组流程。在您的示例中,它将类似于:

function = { text ->
    if (text == "foo"){
        // do side effects here
    } else {
        // do side other side effects
    }
}

通常有几种方法可以将流保持在单个返回路径上,因此您不必做奇怪的事情,例如拥有多个return语句或使用标签。

相关问题