为什么Kotlin MAP不变的关键类型参数?

发布于 2025-02-05 08:07:34 字数 642 浏览 2 评论 0原文

MAP Kotlin中的接口(使用V1.6.21)具有签名,说明

interface Map<K, out V>

为什么k不变而不是协变量(OUT K)?

类型参数的文档k说:

该地图在其密钥类型中是不变的,因为它可以接受密钥作为参数(例如,例如containskey)并将其返回在键集中。

但是,接口set在元素类型中是协变量的,因此最后一部分(“以钥匙集返回”)不适用,至少不是立即。

此外,类型参数k仅在未修改地图状态的出现时使用(方法containskey, get> get ,<代码> getordefault )。在这些地方,使用@unsafevariance是否安全?毕竟,将同一技术用于MAP的值类型参数v,例如containsValue,以允许制作v。协变。

The Map interface in Kotlin (using V1.6.21) has a signature of

interface Map<K, out V>

Why is K invariant instead of covariant (out K)?

The documentation of type parameter K says:

The map is invariant in its key type, as it can accept key as a parameter (of containsKey for example) and return it in keys set.

However, interface Set is covariant in the element type, so the the last part ("return it in keys set") is not applicable, at least not immediately.

Further, the type parameter K is used only at occurrences where the map state is not modified, for lookup purposes (methods containsKey, get, getOrDefault). At these places, isn't it safe to use @UnsafeVariance? After all, that same technique was employed to Map's value type parameter V, for example in containsValue, to allow making V covariant.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一抹微笑 2025-02-12 08:07:35

我的猜测是,使用map&lt; ksubtype,v&gt;作为map&lt; ksupertype,v&gt;(其中ksubtype:ksupertype:ksupertype)不使用确实很有意义,因为前者通过构造无法包含ksubtype以外的键的条目。

因此,适当的实现应从所有调用中返回null get(ksupertype)以及return false从这些调用到containskey(ksupertype) )

set&lt; out e&gt;的情况下,只有包含函数需要不安全的差异,而map也需要获取。与支持用例的价值相比,这可能是一个独特的支持。

My guess would be that using a Map<KSubtype, V> as a Map<KSupertype, V> (where KSubtype : KSupertype) does not really make a lot of sense because the former, by construction, cannot contain entries with keys other than KSubtype.

So a proper implementation should return null from all calls to get(kSupertype) as well as return false from those to containsKey(kSupertype).

In the case of Set<out E> it's only the contains function that needs unsafe variance, and Map would also require unsafe variance on get. This might have been too much of a peculiarity to support, compared to the value of supporting the use case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文