Generics 输出投影类型';ArrayList<*&燃气轮机';禁止使用';public open fun add(索引:Int,元素:E):在java.util.ArrayList'中定义的单元;
我有以下片段:Generics 输出投影类型';ArrayList<*&燃气轮机';禁止使用';public open fun add(索引:Int,元素:E):在java.util.ArrayList'中定义的单元;,generics,kotlin,kotlin-android-extensions,kotlin-extension,Generics,Kotlin,Kotlin Android Extensions,Kotlin Extension,我有以下片段: class RecyclerViewAdapter internal constructor( val clazz: Class<out RecyclerViewViewHolder>, val layout: Int, var dataList: MutableList<*>) ... ... ... fun RecyclerView.getDataList() : ArrayList<*> { return (a
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<*>
}
...
...
...
但我得到了这个错误:
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'
错误:(19,31)Out投影类型“ArrayList”禁止使用
'public open fun add(索引:Int,元素:E):中定义的单位
java.util.ArrayList'
所以我必须向下面这样的人施压:
val personList = (recyclerView.dataList as ArrayList<Person>)
personList.add( 0, Person("Lem Adane", "41 years old", 0))
val personList=(recyclerView.dataList作为ArrayList)
personList.add(0,Person(“Lem Adane”,“41岁”,0))
因为dataList是ArrayList而不是ArrayList,Kotlin在这方面很严格。Kotlin与Java的原始类型不等价。MutableList
中的星号(*)表示您可以安全地从列表中读取值,但无法安全地将值写入列表,因为列表中的值都是未知类型的(例如Person
、String
、Number?
,或者可能是Any?
)。它与MutableList
相同
相反,MutableList
意味着可以从列表中读取和写入任何值。值可以是相同的类型(例如Person
),也可以是混合类型(例如Person
和String
)
在您的情况下,您可能希望使用dataList:MutableList
,这意味着您可以从列表中读取和写入任何非空值
val personList = (recyclerView.dataList as ArrayList<Person>)
personList.add( 0, Person("Lem Adane", "41 years old", 0))