使用布尔值?在如果表达 [英] Use of Boolean? in if expression

查看:90
本文介绍了使用布尔值?在如果表达的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我具有可为空的Boolean b,则可以在Java中进行以下比较:

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 */
}

在Kotlin中,我可以使用!!运算符来实现相同目的:

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?

编辑似乎我简化了一点.对于局部变量,如 Banthar 所示,它确实可以工作.但是,我的布尔b实际上是一个具有后备字段的属性"(我并没有真正加快步伐,但要强加于此).结果是:

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:

推荐答案

您可以使用相等运算符将可空布尔值与truefalsenull进行比较:

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 
}

这篇关于使用布尔值?在如果表达的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆