I am not sure I fully understand the difference between SomeGeneric<*>
and SomeGeneric<Any>
. I think "*" represents anything (wild card) and "Any" represents the object which ALL objects inherit from. So it seems they should be the same, but they are not?
问题:
回答1:
It may be helpful to think of the star projection as a way to represent not just any type, but some fixed type which you don't know what is exactly.
For example, the type MutableList<*>
represents the list of something (you don't know what exactly). So if you try to add something to this list, you won't succeed. It may be a list of String
s, or a list of Int
s, or a list of something else. The compiler won't allow to put any object in this list at all because it cannot verify that the list accepts objects of this type. However, if you attempt to get an element out of such list, you'll surely get an object of type Any?
, because all objects in Kotlin inherit from Any
.
回答2:
In the context I think you imply, SomeGeneric<*>
is equivalent to SomeGeneric<out Any?>
. The Java equivalent is SomeGeneric<? extends Object>
.
The syntax called "star-projections". Here are the official docs: https://kotlinlang.org/docs/reference/generics.html#star-projections