首页 文章

Kotlin仿制药中“*”与“任意”的区别

提问于
浏览
42

我不确定我完全理解 SomeGeneric<*>SomeGeneric<Any> 之间的区别 . 我认为"*"代表任何东西(外卡)而"Any"代表 ALL 对象继承的对象 . 所以看起来它们应该是一样的,但它们不是?

2 回答

  • 61

    star projection视为一种表示不仅仅是任何类型的方法,而是一些你不知道究竟是什么的固定类型可能会有所帮助 .

    例如,类型 MutableList<*> 表示某事物的列表(你不能成功 . 它可能是 String 的列表,或 Int 的列表,或者其他的列表 . 编译器赢了'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肯定得到一个对象类型为 Any? ,因为Kotlin中的所有对象都继承自 Any .

  • 16

    在我认为你暗示的上下文中, SomeGeneric<*> 相当于 SomeGeneric<out Any?> . Java等价物是 SomeGeneric<? extends Object> .

    语法名为"star-projections" . 以下是官方文档:https://kotlinlang.org/docs/reference/generics.html#star-projections

相关问题