gpt4 book ai didi

kotlin - 使用 null 键获取映射

转载 作者:行者123 更新时间:2023-12-03 08:04:34 27 4
gpt4 key购买 nike

当涉及到 map 时,我对 Kotlin 的 null 安全功能感到困惑。我有一个Map<String, String> 。但我可以调用map.get(null)它返回 null指示该键不存在于 map 中。我预计会出现编译器错误,因为 mapMap<String, String>而不是Map<String?, String> 。我怎么可以通过null对于String争论?

还有一个相关的问题:是否有任何类型的 Map,无论是 stdlib 还是第三方实现,都可能会抛出 NullPointerException如果我打电话get(null) ?我想知道调用map.get(s)是否安全而不是s?.let { map.get(it) } ,对于 Map 的任何有效实现.

更新

编译器确实返回了错误 map.get(null) 。但这不是因为空安全,而是因为文字 null不向编译器提供所传递参数类型的指示。我的实际代码更像是这样的:

val map: Map<String, String> = ...
val s: String? = null
val t = map.get(s)

以上编译正常,并返回 null 。为什么 key 应该是 String哪个不可为空?

最佳答案

get Map中的方法声明如下:

abstract operator fun get(key: K): V?

所以对于Map<String, String> ,其 get方法应该只采用 String s。

但是,还有另一个 get 扩展功能,接收器类型为Map<out K, V> :

operator fun <K, V> Map<out K, V>.get(key: K): V?

协变 out K这就是这里的不同之处。 Map<String, String>是一种Map<out String?, String> ,因为StringString? 的子类型。至此get就而言,以狗为键的 map "is"以动物为键的 map 。

val notNullableMap = mapOf("1" to "2")
// this compiles, showing that Map<String, String> is a kind of Map<out String?, String>
val nullableMap: Map<out String?, String> = notNullableMap

这就是为什么你可以传入 String?进入map.get ,其中mapMap<String, String>map被视为“一种”Map<String?, String>因为协变 out K .

And a related question: is there any type of Map, be it a stdlib one or a third-party implementation, that may throw NullPointerException if I call get(null)?

是的,在 JVM 上,TreeMap (使用不处理空值的比较器)不支持空键。比较:

val map = TreeMap<Int, Int>()
println(map[null as Int?]) // exception!

和:

val map = TreeMap<Int, Int>(Comparator.nullsLast(Comparator.naturalOrder()))
println(map[null as Int?]) // null

但是,请注意,由于出现问题 get是每个 Map 上可用的扩展功能,只要您的映射实现 Map,您就无法阻止某人在编译时向您的映射传递可为空的内容.

关于kotlin - 使用 null 键获取映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72832140/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com