java - 为什么这个 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 方法的返回类型显然可以为空,为什么这个条件总是被标记为“真”?
解决方案
这是因为您正在使用!!
运算符并且它返回的所有内容都不为空。如果要检查某些内容是否为 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
推荐阅读
- tensorflow - Tensorflow.js:相同的模型,Python 和浏览器内 JavaScript 之间的预测存在重大差异?
- javascript - 如何将字符串文字传递给javascript中的过滤器函数
- c# - 从静态方法获取标签的文本(已解决)
- javascript - 如何使用 clearInterval()?
- go - Golang 正则表达式替换字符串
- android - Firestore 从集合中查询多个文档
- javascript - dangerouslyGetParent() 从 Tab Navigator 的子屏幕返回 undefined
- c# - Best way to fetch multiple objects from database, based on a list of objects of the same type
- python - 如何根据许多列中的值过滤 Pandas DataFrame?
- javascript - "this" in angular class is undefined after being called in resolve() of a promise