Out-projection类型'ArrayList <*>'禁止使用'public open fun add(index:Int,element:E):java.util.ArrayList中定义的单位'

LEM*_*ANE 20 generics kotlin kotlin-extension kotlin-android-extensions

我有这个片段:

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<*>
}
...
...
...
Run Code Online (Sandbox Code Playgroud)

然后我用它:

recyclerView.getDataList().add(Person("Lem Adane", "41 years old", 0))
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:

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'
Run Code Online (Sandbox Code Playgroud)

mfu*_*n26 32

Kotlin 星形投影不等同于Java的原始类型.在星号(*) MutableList<*>,你可以安全地读取从列表中值,但你不能安全地将数据写到它,因为在列表中的值各为一些未知类型的方式(例如Person,String,Number?,或可能Any?).它是一样的MutableList<out Any?>.

相反,MutableList<Any?>意味着您可以从列表中读取和写入任何值.值可以是相同类型(例如Person)或混合类型(例如PersonString).

在您的情况下,您可能希望使用dataList: MutableList<Any>哪个意味着您可以从列表中读取和写入任何非空值.