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?
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.