防止Kotlin强制Java查看通配符类型 [英] Prevent Kotlin from forcing Java to see a wildcard type
问题描述
这很好:
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
?
推荐答案
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屋!