我在看the docs http://kotlinlang.org/docs/reference/control-flow.html从 Kotlin 网站来看,控制流表达式只有两个:if
and when
.
For if
:
该表达式需要有一个else
branch
For when
:
The else
如果没有满足其他分支条件,则评估分支。如果when
用作表达式,则else
分支是强制性的,除非编译器可以证明所有可能的情况都包含分支条件。
Question
所以似乎没有办法在不覆盖所有分支的情况下制作控制流表达式,是吗?如果没有,有没有办法让控制流表达式错过一些分支;如果是这样,为什么?
将会出现以下代码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())
}
}
}
但是下面的代码通过编译......
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())
}
}
}
这里的技巧是不要使用if
作为一种表达方式。我的猜测是你放置了if
at a let
块,它返回最后一个语句,从而使用if
,从而将其视为一个表达式。
我建议扔掉let
函数(无论如何这里都没用):
override fun onReceive(context: Context?, intent: Intent?) {
if(intent != null) {
if (intent.action == MySDK.BROADCAST_ACTION_LOGIN) {
mListener.get()?.loggedOn(LoggedOnUserInfo.IT)
} else if (intent.action == MySDK.BROADCAST_ACTION_LOGOUT) {
mListener.get()?.loggedOut(LoggedOutUserInfo())
}
}
}
你的第二个版本编译是因为context!!.unregisterReceiver(this)
有一个不同的类型mListener.get()?.loggedOut(LoggedOutUserInfo())
,这使得类型不匹配并阻止使用if
作为一种表达方式。
P.S.
Kotlin 有很多强大的控制结构。我个人更喜欢这个版本:
override fun onReceive(context: Context?, intent: Intent?) {
intent ?: return
when(intent.action) {
MySDK.BROADCAST_ACTION_LOGIN -> mListener.get()?.loggedOn(LoggedOnUserInfo.IT)
MySDK.BROADCAST_ACTION_LOGOUT -> mListener.get()?.loggedOut(LoggedOutUserInfo())
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)