Issue
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 are they?
Solution
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
.
From asco comment below:
Additionally
List<*>
can contain objects of any type, but only that type, so it can contain Strings (but only Strings), whileList<Any>
can contain Strings and Integers and whatnot, all in the same list.
Answered By - Alexander Udalov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.