Kotlin setOnclickListener

前端 未结 2 1673
夕颜
夕颜 2021-02-09 01:19

Back in java I used to write only return for a void method... But kotlin doesn\'t seem to allow just return, instead it uses return@methodname? Can som

相关标签:
2条回答
  • 2021-02-09 01:29

    When inside a lambda, you have to specify which scope you wish to return from, because it might be ambiguous. See the official docs about returning at labels.

    In this specific case, if you'd be returning at the end of a function that returns nothing, you can omit the return statement altogether.

    0 讨论(0)
  • 2021-02-09 01:53

    From kotlinlang website:

    Return at Labels

    With function literals, local functions and object expression, functions can be nested in Kotlin. Qualified returns allow us to return from an outer function. The most important use case is returning from a lambda expression. Recall that when we write this:

    fun foo() {
        ints.forEach {
            if (it == 0) return  // nonlocal return from inside lambda directly to the caller of foo()
            print(it)
        }
    }
    

    The return-expression returns from the nearest enclosing function, i.e. foo. (Note that such non-local returns are supported only for lambda expressions passed to inline functions.) If we need to return from a lambda expression, we have to label it and qualify the return:

    fun foo() {
        ints.forEach lit@ {
            if (it == 0) return@lit
            print(it)
        }
    }
    

    Now, it returns only from the lambda expression. Oftentimes it is more convenient to use implicits labels: such a label has the same name as the function to which the lambda is passed.

    fun foo() {
        ints.forEach {
            if (it == 0) return@forEach
            print(it)
        }
    }
    
    0 讨论(0)
提交回复
热议问题