0

I have this following function.

    private val onConnect = Emitter.Listener {
    if(fromReconnect) {
        return
    }
    Log.d("Socket", "Socket Connected")
    val hndlr = Handler(Looper.getMainLooper())
    hndlr.post{ Toast.makeText(applicationContext, "Socket Connected", Toast.LENGTH_SHORT).show() }
    if (isTryLogin){
        reLogin()
    }
}

I am trying to return from the function if fromReconnect flag is set. But Android Studio is throwing return not allowed here error. But when I change return to return@Listener it's working fine.The IDE hints it's an anonymous function. Why do we need to return@Listener this instead of just return?

  • Related [Kotlin: Whats does “return@” mean?](https://stackoverflow.com/questions/40160489/kotlin-whats-does-return-mean) – AskNilesh Sep 21 '18 at 03:54
  • @NileshRathod, Thanks. I could understand the need for **@** in nested functions & loops. For non-return functions, why do we need that? Even in that post, there's no answer for that. Do you mind to give some explanation? –  Sep 21 '18 at 04:05
  • 1
    here is your answer my friend https://stackoverflow.com/questions/46845729/kotlin-setonclicklistener – AskNilesh Sep 21 '18 at 04:24
  • 1
    @NileshRathod. Thank you..Interesting finding for me today :) –  Sep 21 '18 at 04:45

1 Answers1

0

Kotlin allows non-local return only inside inline functions. If your function is not marked as inline, or lambda parameter is marked noinline or crossinline than you cannot use the return statement, only return with a label. Because of non-local return - returns from caller function and not from lambda exactly.

You can find additional inforamtion in the documentation. https://kotlinlang.org/docs/reference/returns.html