防止Kotlin强制Java查看通配符类型 [英] Prevent Kotlin from forcing Java to see a wildcard type

查看:58
本文介绍了防止Kotlin强制Java查看通配符类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很好:

class Wrapped<out T>(val value: T)

open class Wrapper<T> {
    fun wrap(map: T): Wrapped<T> = Wrapped(map)
}

class Wrapper2 : Wrapper<Map<String, String>>()

val wrapped: Wrapped<Map<String, String>> = Wrapper2().wrap(mapOf())

但是,当我尝试从Java访问Wrapper2.wrap时,Map会返回通配符类型:

But, when I try to access Wrapper2.wrap from Java, the Map comes back with a wildcard type:

    Map<String, String> toWrap = new HashMap<>();
    Wrapped<Map<String, String>> result;
    result = new Wrapper<Map<String, String>>().wrap(toWrap); // ok
    result = new Wrapper2().wrap(toWrap); // NOT ok, returns Wrapped<Map<String, ? extends String>>

我可以通过使用显式类型覆盖Wrapper2中的wrap来解决此问题.

I can work around this by overriding wrap in Wrapper2 with the explicit type.

为什么Wrapper2.wrap返回的类型与Wrapper.wrap不同?

Why does Wrapper2.wrap return a different type than Wrapper.wrap?

推荐答案

您可以使用泛型中的通配符来抑制Kotlin,例如

You can suppress Kotlin using wildcards in generics as described in the Kotlin reference where it describes the @JvmSuppressWildcards annotation (or the reverse of that @JvmWildcard annotation).

从文档中

另一方面,如果不需要在生成通配符的地方使用通配符,则可以使用@JvmSuppressWildcards:

fun unboxBase(box: Box<@JvmSuppressWildcards Base>): Base = box.value
// is translated to 
// Base unboxBase(Box<Base> box) { ... }

注意:@JvmSuppressWildcards不仅可用于单个类型参数,而且可用于整个声明(例如函数或类),从而使其中的所有通配符均被抑制.

NOTE: @JvmSuppressWildcards can be used not only on individual type arguments, but on entire declarations, such as functions or classes, causing all wildcards inside them to be suppressed.

这篇关于防止Kotlin强制Java查看通配符类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆