本文介绍了"*"和"*"之间的差异.和“任何"在Kotlin仿制药中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定我是否完全理解SomeGeneric<*>SomeGeneric<Any>之间的区别.我认为*代表任何内容(通配符),而Any代表 ALL 对象继承的对象.看来它们应该是相同的,但是对吗?

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?

推荐答案

考虑星形投影不仅可以表示任何类型,还可以表示某些不知道确切类型的固定类型.

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.

例如,类型MutableList<*>表示某物的列表(您不知道到底是什么).因此,如果您尝试向此列表添加内容,则不会成功.它可以是String的列表,也可以是Int的列表,或其他内容的列表.编译器根本不允许将任何对象放入此列表,因为它无法验证列表是否接受此类型的对象.但是,如果您尝试从此类列表中删除元素,则肯定会得到Any?类型的对象,因为Kotlin中的所有对象都继承自Any.

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.

来自 asco 以下评论:

From asco comment below:

这篇关于"*"和"*"之间的差异.和“任何"在Kotlin仿制药中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:19