Out-projected type'ArrayList <*>'禁止使用'public open fun add(index:Int,element:E):java.util.ArrayList'
我有这个片段:
class RecyclerViewAdapter internal constructor( val clazz: Class<out RecyclerViewViewHolder>, val layout: Int, var dataList: MutableList<*>) ... ... ... fun RecyclerView.getDataList() : ArrayList<*> { return (adapter as RecyclerViewAdapter).dataList as ArrayList<*> } ... ... ...
那么我使用这个:
recyclerView.getDataList().add(Person("Lem Adane", "41 years old", 0))
但我得到这个错误:
Error:(19, 31) Out-projected type 'ArrayList<*>' prohibits the use of 'public open fun add(index: Int, element: E): Unit defined in java.util.ArrayList'
Kotlin 星形投影不等同于Java的原始类型。 MutableList<*>
的星号(*)表示您可以安全地从列表中读取值,但不能安全地向其写入值; 列表值都是一些未知的类型,可能是Person
, String
, Number?
,甚至Any?
。 即它与MutableList<out Any?>
。
相比之下, MutableList<Any?>
意味着您可以读取和写入列表中的任何值。 所有的值可能是相同的类型(例如Person
),但是它们可以是混合类型(例如Person
和String
)。
在你的情况下,你可能想要使用dataList: MutableList<Any>
这意味着你可以读取和写入列表中的任何非空值。
所以我必须投给像下面这样的人:
val personList = (recyclerView.dataList as ArrayList<Person>) personList.add( 0, Person("Lem Adane", "41 years old", 0))
因为dataList是ArrayList <*>而不是ArrayList,Kotlin严格。