为什么 nullable cursor.getString() 赋值给非 nullable String 会编译?

Why does nullable cursor.getString() assignment to non-nullable String compile?

我有这个代码:

data class Site(val apikey: String, val id: Int) {
    companion object {
        val INVALID = Site("", 0)
    }

    lateinit var name: String
    lateinit var city: String
    lateinit var country: String
}

然后,稍后在我的代码中,我为 site.city 分配一个来自 SQLite 数据库的值:

site.city = cursor.getString(3)

我假设这不会编译,因为 cursor.getString returns 可以为 null String,并且 Kotlin 的字符串默认情况下不可为 null。然而,这编译正常,但在运行时崩溃:

java.lang.IllegalStateException: cursor.getString(3) must not be null

因为cursor.getString(3) returns null(这是有效的,数据不在数据库中)。我检查了调试器,getString() 调用工作正常。

如果 Java 方法未使用 @Nullable@NonNull 注释,Kotlin 会将其视为 platform type,并让您将其分配给可空或不可为空的变量,由您自行决定。使用正确的类型取决于您。

CursorgetString 方法的特定情况下,它没有以任何方式注释,也不应该 - the documentation 表示 [=12] 的实现=] 接口可以选择是否抛出异常或 return null 在错误情况下:

The result and whether this method throws an exception when the column value is null or the column type is not a string type is implementation-defined.