Home > OS >  Why is this Kotlin condition marked as always 'true'?
Why is this Kotlin condition marked as always 'true'?

Time:10-28

I have this bit of code to check if my mongoDB connection is still active:

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

I get a warning saying this condition is always true:

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

I know that Kotlin has nullable types, but the getDatabase() method is referencing a Java method inside MongoClient. I'm using jdk-8u291 which doesn't have nullable return types for Java as far as I'm aware (excluding the @Nullable annotation). Here's the decompiled MongoClient::getDatabase() method:

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);

   // ...
}

Why is this condition marked as always "true" if the return type of the Java method is obviously nullable?

CodePudding user response:

this is because you are using the !! operator and everything that it returns is not null. If you want to check if something is null you have to use the ? operator:

instance?.connection != null

The !! operator checks if something is null and if it is null it will throw. Therefore if you use the instance after that operator it will not be null anymore.

You could also make use of the let function, something like:

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

CodePudding user response:

Is because MongoDatabase getDatabase(String databaseName); is not marked with @Nullable. So that type is not nulable for Kotlin.

And since you are saying everything is not nullable !! then the result is not returned null by the shorthand ? which you are not using.

  • Related