Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin setOnclickListener

Tags:

android

kotlin

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 someone explain what this is and how does it add value?

 bAddLine.setOnClickListener {
            val selectedSeries = getSelectedSeries()
            if (selectedSeries.isEmpty()) {
                Toast.makeText(this, getString(R.string.toast_channel_mandatory), Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
        }
like image 369
Audi Avatar asked Oct 20 '17 09:10

Audi


1 Answers

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)
    }
}
like image 178
AlexTa Avatar answered Oct 12 '22 22:10

AlexTa