【发布时间】:2020-10-13 16:33:41
【问题描述】:
Kotlin 1.4.0
解决需要布尔值但找到布尔值的条件?
我有以下代码:
detailList.firstOrNull()?.postCode.takeIf { postcode: String? ->
postcode?.run { this != ZERO }
}?.also { postcode ->
view.editTextPostcode.setText(postcode)
}
这里我收到一条错误消息,上面写着required Boolean found Boolean?
由于邮政编码可能为空,我想知道为什么它不能智能地转换为非空。
这通过删除安全调用运算符来工作
detailList.firstOrNull()?.postCode.takeIf { postcode: String? ->
postcode.run { this != ZERO }
}?.also { postcode ->
view.editTextPostcode.setText(postcode)
}
在上面,如果邮政编码真的为空,这不会崩溃吗?
这是我在检查 null 然后评估第二个条件时使用的代码:
detailList.firstOrNull()?.postCode.takeIf { postcode: String? ->
postcode != null && postcode != ZERO
}?.also { postcode ->
view.editTextPostcode.setText(postcode)
}
正如@Steyrix 在他的评论中指出的那样,如果邮政编码真的为空,那么就不会对条件进行评估。
这是将评估条件并返回 true 布尔值的更新。如果 postcode 为 null 则返回 false
detailList.firstOrNull()?.postCode.takeIf { postcode: String? ->
postcode?.run {
postcode != ZERO
} ?: false
}?.also { postcode ->
view.editTextPostcode.setText(postcode)
}
【问题讨论】:
-
在第一种情况下它不是智能转换为非空值,因为您明确将其声明为可为空类型的变量吗?如果post code可以为null,则不能有布尔表达式求值,所以不能有boolean。
-
您所说的很有意义,并用可能的解决方案更新了我的问题。如果邮政编码不为空,则只能返回布尔值。如果邮政编码为空,则不进行评估。然而,只有一个问题。如果邮政编码为空,它将跳过评估,在这种情况下,为什么 IDE 说需要
Boolean but found Boolean?我会认为它会找到Unit,因为最后一条语句没有返回任何内容?谢谢 -
发生这种情况是因为在可空实例上执行类型化方法将返回空,如果该实例实际上为空。例如。
object?.intMethod将返回 null 作为Int?。object?.boolMethod将返回 null 作为Boolean?。由于没有可为 null 的 Unit,编译器将 type 定义为方法的可为 null 的返回类型。 -
@Steyrix 你能创建它作为答案,以便我可以将此问题标记为已解决
-
是的,当然。我发布了一个答案
标签: kotlin