首页 > 解决方案 > 为什么这个 Kotlin 条件总是被标记为“真”?

问题描述

我有这段代码来检查我的 mongoDB 连接是否仍然处于活动状态:

val isConnected: Boolean
            get() = if (instance!!.connection != null) {
                try {
                    instance!!.connection!!.getDatabase(instance!!.databaseName!!) != null
                } catch (e: Exception) {
                    Logger.handle("Error verifying mongoDB connection status", e)
                    false
                }
            } else false

我收到警告说这种情况总是正确的:

Condition 'instance!!.connection!!.getDatabase(instance!!.databaseName!!) != null' is always 'true'

我知道 Kotlin 具有可为空的类型,但 getDatabase() 方法引用了 MongoClient 中的 Java 方法。我正在使用 jdk-8u291,据我所知,它没有 Java 的可为空返回类型(不包括 @Nullable 注释)。这是反编译的 MongoClient::getDatabase() 方法:

public interface MongoClient extends Closeable {

    
    /**
     * Gets a {@link MongoDatabase} instance for the given database name.
     *
     * @param databaseName the name of the database to retrieve
     * @return a {@code MongoDatabase} representing the specified database
     * @throws IllegalArgumentException if databaseName is invalid
     * @see MongoNamespace#checkDatabaseNameValidity(String)
     */
    MongoDatabase getDatabase(String databaseName);

   // ...
}

如果 Java 方法的返回类型显然可以为空,为什么这个条件总是被标记为“真”?

标签: javakotlinnullnullable

解决方案


这是因为您正在使用!!运算符并且它返回的所有内容都不为空。如果要检查某些内容是否为 null,则必须使用?运算符:

instance?.connection != null

运算符检查某些内容!!是否为 null,如果为 null,则将抛出。因此,如果您在该运算符之后使用实例,它将不再为空。

您还可以使用该let功能,例如:

val isConnected: Boolean
    get() = instance?.let {
            try {
                it.connection?.getDatabase(it.databasename) != null
            }  catch (e: Exception) {
                Logger.handle("Error verifying mongoDB connection status", e)
                false
            }
        } ?: false

推荐阅读