Hey guys. I know a little bit about `qualified thi...
# android
c
Hey guys. I know a little bit about
qualified this
but I am trying to wrap my brains around this syntax right here:
Copy code
Observer { loginFormState ->
                if (loginFormState == null) {
                    return@Observer
                }
                loginButton.isEnabled = loginFormState.isDataValid
                loginFormState.usernameError?.let {
                    usernameEditText.error = getString(it)
                }
                loginFormState.passwordError?.let {
                    passwordEditText.error = getString(it)
                }
            })
I understand the rest of the code except what is happening here:
Copy code
if (loginFormState == null) {
     return@Observer
  }
What would be the interpretation of what
return@Observer
mean? Semantics?
c
Thanks @ephemient I remember doing this type of thing in Pascal with a
goto
. Same principal right?
e
no
c
Is it like
continue
in other languages?
e
Observer { ... }
is an anonymous object like
Copy code
object Observer {
    fun observe(loginFormState) {
        if (loginFormState == null) {
            return
or a function taking a lambda, can't tell without more context, but the code behavior is similar either way
c
Here is the full context:
Copy code
loginViewModel.loginFormState.observe(viewLifecycleOwner,
            Observer { loginFormState ->
                if (loginFormState == null) {
                    return@Observer
                }
                loginButton.isEnabled = loginFormState.isDataValid
                loginFormState.usernameError?.let {
                    usernameEditText.error = getString(it)
                }
                loginFormState.passwordError?.let {
                    passwordEditText.error = getString(it)
                }
            })
If I understand the docs, it is a way of returning to a specific point in code. So in this case it returns back to that place labelled
Observer
and then keeps waiting.
Am I right?
e
no
c
Is it like exiting a named anonymous function?
e
a bare
return
always means "return from the enclosing `fun`". there are cases where this is either not the intended behavior (intentional early return within an inline lambda) or impossible (non-inline lambda, SAM/`fun interface`), where you would use
return@
. this case is a SAM
c
What is SAM?
c
I see. With your explanation, I can now notice that
Observer
is not a
label
but some functional interface and it is being instantiated via lambda expression hence the need to use the
return@
in order to return early. Did I now get you right?
e
yes. in this case you cannot use
return
at all, because the observer outlives the function
🙏 1
c
Tough stuff! Let me read a little bit more, but thank you very much for the help.