为什么Kotlin在一种情况下会推断Java返回的类型是可为null的,而在另一种情况下,它可以是可为null的,也可以是不可为null的?
我已经判断了HashMap.get
和JsonNode.get
,无论是在CALSS中还是在继承链的任何地方,我都无法识别任何类似于@NotNull的注释.是什么让Kotlin对这两个电话的处理方式有所不同?
我已经阅读了文档https://kotlinlang.org/docs/java-interop.html#null-safety-and-platform-types,但it解释使用了"平台类型",而没有解释这些类型是什么,而且它也没有解释行为上的差异.
import com.fasterxml.jackson.databind.JsonNode
private fun docType(node: JsonNode, map: java.util.HashMap<String,String>) {
val x: JsonNode = node.get("doc_type") // DOES compile and can throw NPE at runtime
val y: JsonNode? = node.get("doc_type") // DOES compile and Kotlin's type system will force you to check for null
val z: String = map.get("a") // ERROR: Type mismatch: inferred type is String? but String was expected
}