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

问题描述 投票:0回答:1

有一个带有可空布尔值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>```
kotlin nullable equality
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.