kotlin 如何检查可为空的布尔值?
kotlin how does the checking of a nullable boolean work?
有一个 class Config
可以为空的布尔值 sAllowed
和一个接口函数 returns 一个可以为空的配置
interface IConfig {
fun getConfig() : Config?
}
class Config (var sAllowed: Boolean?=null)
以及何时要使用此布尔值:
var sAllowed = false
// some loop ...
val config = iConfig.getConfig()
if (config != null) {
sAllowed = sAllowed || config.sAllowed == true
}
但是 config.sAllowed == true
转换为:
Intrinsics.areEqual(config.getsAllowed(), true);
和Intrinsics.areEqual(config.getsAllowed(), true);
是:
public static boolean areEqual(Object first, Object second) {
return first == null ? second == null : first.equals(second);
}
first.equals(second);
是:
public boolean equals(Object obj) {
return (this == obj);
}
equals(Object obj)
的文档是 Indicates whether some other object is "equal to" this one
,而不是值相等。
听起来 config.sAllowed == true
是在检查对象相等性而不是值,还是我在这里遗漏了什么?
* The {@code equals} method for class {@code Object} implements
* the most discriminating possible equivalence relation on objects;
* that is, for any non-null reference values {@code x} and
* {@code y}, this method returns {@code true} if and only
* if {@code x} and {@code y} refer to the same object
* ({@code x == y} has the value {@code true}).
* <p>```
正在检查对象是否相等。但是看看 Boolean.java
的 equals()
public boolean equals(Object obj) {
if (obj instanceof Boolean) {
return value == ((Boolean)obj).booleanValue();
}
return false;
}
这确实考虑了包装器包装的值 class。
first.equals(second);
将在 Boolean
而不是 Object
上调用 equals
,因为 first
是 Boolean
。
有一个 class Config
可以为空的布尔值 sAllowed
和一个接口函数 returns 一个可以为空的配置
interface IConfig {
fun getConfig() : Config?
}
class Config (var sAllowed: Boolean?=null)
以及何时要使用此布尔值:
var sAllowed = false
// some loop ...
val config = iConfig.getConfig()
if (config != null) {
sAllowed = sAllowed || config.sAllowed == true
}
但是 config.sAllowed == true
转换为:
Intrinsics.areEqual(config.getsAllowed(), true);
和Intrinsics.areEqual(config.getsAllowed(), true);
是:
public static boolean areEqual(Object first, Object second) {
return first == null ? second == null : first.equals(second);
}
first.equals(second);
是:
public boolean equals(Object obj) {
return (this == obj);
}
equals(Object obj)
的文档是 Indicates whether some other object is "equal to" this one
,而不是值相等。
听起来 config.sAllowed == true
是在检查对象相等性而不是值,还是我在这里遗漏了什么?
* The {@code equals} method for class {@code Object} implements
* the most discriminating possible equivalence relation on objects;
* that is, for any non-null reference values {@code x} and
* {@code y}, this method returns {@code true} if and only
* if {@code x} and {@code y} refer to the same object
* ({@code x == y} has the value {@code true}).
* <p>```
正在检查对象是否相等。但是看看 Boolean.java
equals()
public boolean equals(Object obj) {
if (obj instanceof Boolean) {
return value == ((Boolean)obj).booleanValue();
}
return false;
}
这确实考虑了包装器包装的值 class。
first.equals(second);
将在 Boolean
而不是 Object
上调用 equals
,因为 first
是 Boolean
。