Kotlin如何检查可为空的布尔值?

时间:2019-03-15 13:22:00

标签: kotlin nullable equality

具有一个带有可空布尔值Config的类sAllowed和一个接口函数,将返回一个可空配置

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>```

1 个答案:

答案 0 :(得分:1)

正在检查对象是否相等。不过请看equals()

Boolean.java
public boolean equals(Object obj) {
        if (obj instanceof Boolean) {
            return value == ((Boolean)obj).booleanValue();
        }
        return false;
    }

这确实考虑了Wrapper类包装的值。

first.equals(second);

由于equalsBoolean,因此将在Object而不是first上调用Boolean