我们需要更多代码才能给你一个完整的答案,但我可以尝试假设并给你最接近的答案。
when有两种使用方式
- 独立
- 作为表达式
如果您将其用作switch,即根据具体情况执行不同的操作
您不需要返回值,也不需要else 语句
例如:
when (menuItem.id) { /** I guess you're trying to perform differet actions based on menu item click */
R.id.menu_share -> {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://web.whatsapp.com"))
startActivity(intent)
} /** returns Unit */
R.id.menu_info -> {
Toast.makeText(this,"Ada Toast", Toast.LENGTH_LONG).show()
} /** returns Unit */
} /** result ignores / Unit */
您使用when 的另一种方式是作为表达式,此时您希望语句返回一个值。
在这种情况下,您必须为您提供的类型填写所有可能的情况,如果类型是您无法验证所有其他选项的类型,则必须填写 else,例如 Int、String
例如:
val result = when (menuItem.id) { /** I guess you're trying to perform different actions based on menu item click */
R.id.menu_share -> {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://web.whatsapp.com"))
startActivity(intent)
} /** Type mismatch: inferred type is Unit but Boolean was expected */
R.id.menu_info -> {
Toast.makeText(this,"Ada Toast", Toast.LENGTH_LONG).show()
} /** Type mismatch: inferred type is Unit but Boolean was expected */
else -> false /** returns Boolean */
} /** Type mismatch: inferred type is Unit but Boolean was expected */
要解决此问题,您需要在所有情况下都返回相同的类型
val result = when (menuItem.id) { /** I guess you're trying to perform different actions based on menu item click */
R.id.menu_share -> {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://web.whatsapp.com"))
startActivity(intent)
true
} /** returns Boolean */
R.id.menu_info -> {
Toast.makeText(this,"Ada Toast", Toast.LENGTH_LONG).show()
true
} /** returns Boolean */
else -> false /** returns Boolean */
} /** returns Boolean */
希望我的解释能回答你的问题,如果没有,欢迎你发表评论。