使用布尔值?在 if 表达式中 [英] Use of Boolean? in if expression
问题描述
如果我有一个可为空的 Boolean b
,我可以在 Java 中进行以下比较:
Boolean b = ...;如果 (b != null && b) {/* 做一点事 */} 别的 {/* 做别的事情 */}
在 Kotlin 中,我可以通过使用 !!
操作符来实现相同的效果:
val b:布尔值?= ...if (b != null && b!!) {/* 做一点事 */} 别的 {/* 做别的事情 */}
然而,!!
的使用让我感觉有点粗略,绕过了零安全系统.
对此有更优雅的方法吗?
<小时>编辑 看来我有点过于简单化了.对于局部变量,正如
You can compare nullable boolean with true
, false
or null
using相等运算符:
var b:布尔值?= 空如果 (b == 真) {//b 不为空且等于真}如果(b == 假){//b 是假的}如果 (b != 真) {//b 为空或假}
If I have a nullable Boolean b
, I can do the following comparison in Java:
Boolean b = ...;
if (b != null && b) {
/* Do something */
} else {
/* Do something else */
}
In Kotlin, I can achieve the same by using the !!
operator:
val b: Boolean? = ...
if (b != null && b!!) {
/* Do something */
} else {
/* Do something else */
}
However, the use of !!
feels a bit sketchy to me, circumventing the null safety system.
Is there a more elegant approach for this?
Edit It seems I oversimplicated a bit. For local variables, as Banthar shows, it does work. However, my Boolean b
is actually a "property with a backing field" (I'm not really up to speed yet what this imposes). This is the result:
You can compare nullable boolean with true
, false
or null
using equality operator:
var b: Boolean? = null
if (b == true) {
// b was not null and equal true
}
if (b == false) {
// b is false
}
if (b != true) {
// b is null or false
}
这篇关于使用布尔值?在 if 表达式中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!