Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

Difference between "*" and "Any" in Kotlin generics

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 Strings, or a list of Ints, 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), while List<Any> can contain Strings and Integers and whatnot, all in the same list.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...