25

我有这个片段:

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'
4

2 回答 2

38

Kotlin星形投影不等同于 Java 的原始类型。中的星号 (*)MutableList<*>表示您可以安全地从列表中读取值,但不能安全地向其写入值,因为列表中的每个值都是某种未知类型(例如PersonStringNumber?或可能Any?)。它与 相同MutableList<out Any?>

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

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

于 2016-11-10T13:55:15.470 回答
3

所以我必须投给像下面这样的人:

val personList = (recyclerView.dataList as ArrayList<Person>)
personList.add( 0, Person("Lem Adane", "41 years old", 0))

因为 dataList 是 ArrayList<*> 而不是 ArrayList 并且 Kotlin 对此很严格。

于 2016-11-10T05:10:21.813 回答