I looked at the docs from Kotlin website, there are only two Control-Flow expressions: if
and when
.
For if
:
the expression is required to have an
else
branch
For when
:
The
else
branch is evaluated if none of the other branch conditions are satisfied. Ifwhen
is used as an expression, theelse
branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions.
Question
So it seems that there is no way to make a Control-Flow expression without covering all branches, Is it right? If not, Is there any way to make a Control-Flow expression to miss some branches; If so, why?
Following code will occur if must have both main and 'else' branches if used as an expression
override fun onReceive(context: Context?, intent: Intent?) {
intent?.let {
if (it.action == MySDK.BROADCAST_ACTION_LOGIN) {
mListener.get()?.loggedOn(LoggedOnUserInfo.IT)
}else if (it.action == MySDK.BROADCAST_ACTION_LOGOUT) {
// Occur 'if must have both main and 'else' branches if used as an expression'
mListener.get()?.loggedOut(LoggedOutUserInfo())
}
}
}
But following code pass compile.....
override fun onReceive(context: Context?, intent: Intent?) {
intent?.let {
if (it.action == MySDK.BROADCAST_ACTION_LOGIN) {
mListener.get()?.loggedOn(LoggedOnUserInfo.IT)
context!!.unregisterReceiver(this) // only add this line to test.
}else if (it.action == MySDK.BROADCAST_ACTION_LOGOUT) {
mListener.get()?.loggedOut(LoggedOutUserInfo())
}
}
}
val foo = if (someCondition) "bar" else "baz"
. – Pelorusif
as statement, it won't requireelse
. – Hinayana