Java通配符类型与Kotlin Star-projection [英] Java Wildcard-types vs Kotlin Star-projection
问题描述
我正在阅读关于Java和Koltin之间差异的kotlin文档,这里
https://kotlinlang.org/docs/reference/comparison-to-java.html 。据说那里 Koltin没有通配符类型。但仔细阅读泛型文档后,我发现有关
的信息明星投影,说实话,我看不出有什么不同。有人可以向我解释这是怎么回事
List<?>列表;
不同于此
lateinit var list:MutableList< *>
可能是Kotlin没有通配符的形式与它们在Java中的形式相同。相反,Kotlin使用了混合站点差异的不同概念,添加了一个选项来指定声明站点的变化,这是用Java通配符无法做到的。
至于星形投影,它实际上几乎等同于一个无界的Java通配符。但是,至少有一个与Kotlin类型系统有关的差异。
如果您有 List<?> $ c $类型对于Java来说是未知的,但所有的Java引用类型都是可空的,因此可以安全地将
null
作为未知类型的参数传递,例如 list.add(null)
。
在Kotlin中不是这样,一个明星投影 MutableList< />
在Nothing 投影中将 out Any
和后者意味着你不能将任何东西传递给类型未知的方法(
Nothing
是没有值的类型)。
对于超额预测也是如此:虽然可以将 null
作为Java有界通配符类型传递?对T
进行扩展,你不能对Kotlin out T
投影做同样的处理。 Java无界通配符的确切等价物是< in Nothing?>
,因为它允许您传递 null
作为未知类型的参数( Nothing?
是 Nothing
∪{ null
},这是只有 null
值的类型。)
I was reading a kotlin documentation about differences between Java and Koltin here https://kotlinlang.org/docs/reference/comparison-to-java.html. It was stated there that Koltin does not have wildcard-types. However after reading carefully through the documentation of generics I have found information about star-projection and honestly I can't see the difference. Can somebody explain to me how this
List<?> list;
differs from this
lateinit var list: MutableList<*>
Probably what it means is that Kotlin doesn't have wildcards in the same form as they are present in Java. Instead, Kotlin uses a different concept of mixed-site variance, which adds an option to specify the variance at declaration-site, that is something you cannot do with Java wildcards.
As to the star-projection, it is actually almost equivalent to an unbounded Java wildcard. However, there is at least one difference related to the Kotlin type system.
When you have a List<?>
, the type is unknown to Java, but all Java referential types are nullable, and therefore you can safely pass a null
as an argument of the unknown type, e.g. list.add(null)
.
In Kotlin that is not true, a star projection MutableList<*>
combines both out Any?
and in Nothing
projections, and the latter means that you cannot pass anything at all to the methods where the type is unknown (Nothing
is the type that has no value).
The same can be said of the out-projections: while you can pass a null
as a Java bounded wildcard type ? extends T
, you cannot do the same with Kotlin out T
projection.
And the exact equivalent of the Java unbounded wildcard is <in Nothing?>
, because it lets you pass a null
as an argument of the unknown type (Nothing?
is Nothing
∪ { null
}, this is the type that has only null
value).
这篇关于Java通配符类型与Kotlin Star-projection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!