cluster1
cluster1

Reputation: 5684

return@methodName - Meaning of that syntax?

This code is from an Udemy-course I'm currently doing:

if (noteTitle.isNullOrEmpty()) {
    title_et.error = "Title required"
    return@setOnClickListener
}

What it is basically doing is clear to me. But what's that 'return@setOnClickListener' statement?

What's the meaning of these @method-name syntax? What means the @-character here?

Upvotes: 1

Views: 59

Answers (1)

Animesh Sahu
Animesh Sahu

Reputation: 8096

Its qualified returns.

Consider the following code:

fun foo(strings: List<String?>) {
    strings.forEach {
        if (it.isEmptyOrNull()) return
        println(it)
    }
}

Since forEach is an inline function, return statement will return from the parent function foo instead.

To simply return from one iteration of forEach you qualify to return only on a particular scope:

strings.forEach {
    if (it.isEmptyOrNull()) return@forEach
    // ...
}

You can customize it with other name if they are ambiguous:

strings.forEach outer@ { a ->
    list2.forEach inner@ { b ->
        if (a.isEmptyOrNull()) return@outer
        // ...
    }
}

This is useful mostly in inline and cross-inline situations, but sometimes you also want to explicitly qualify in non-inline lambdas (just to be more precise) as in the example you mentioned.

Upvotes: 1

Related Questions