我在https://kotlinlang.org/docs/reference/control-flow.html中看到了这个片段
when (x) {
parseInt(s) -> print("s encodes x")
else -> print("s does not encode x")
}
我感到困惑,第一种情况是
x.parseInt(s)
还是其他。我问的原因是因为,我尝试了以下
when(myString)) {
isNullOrBlank() -> removeValue()
else -> setValue(myString)
}
它在
isNullOrBlack()
中失败。我尝试以下也失败。
when(myString)) {
it.isNullOrBlank() -> removeValue()
else -> setValue(it)
}
最佳答案
第一种情况是检查x
是否等于调用parseInt(x)
的结果,这不是x
的功能。
将计算为表达式的任何大小写与x
进行相等性检查。无法创建一种情况,您需要在when语句的目标上调用一个函数,如果该函数返回true,则该函数通过。使用目标时,您唯一的选择是检查其相等性,检查它是否是in
或检查它是否是is
。
要执行您要尝试的操作,您需要一个没有目标的when语句。
when {
myString.isNullOrBlank() -> removeValue()
else -> setValue(myString)
}
关于kotlin - 如何在Kotlin中将WHEN用于表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61134251/