外投影类型 'ArrayList<*>' 禁止使用 'public open fun add(index: Int, element: E): Unit defined in java.util.ArrayList'
Out-projected type 'ArrayList<*>' prohibits the use of 'public open fun add(index: Int, element: E): Unit defined in 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'
所以我必须投给如下的人:
val personList = (recyclerView.dataList as ArrayList<Person>)
personList.add( 0, Person("Lem Adane", "41 years old", 0))
因为 dataList 是 ArrayList<*> 而不是 ArrayList 并且 Kotlin 对此很严格。
Kotlin star-projections 不等同于 Java 的原始类型。 MutableList<*>
中的星号 (*) 表示您可以安全地从列表中读取值,但不能安全地将值写入其中,因为列表中的每个值都是某种未知类型(例如 Person
、String
、Number?
,或者可能 Any?
)。与 MutableList<out Any?>
.
相同
相比之下,MutableList<Any?>
意味着您可以从列表中读取和写入任何值。这些值可以是相同类型(例如 Person
)或混合类型(例如 Person
和 String
)。
在您的情况下,您可能希望使用 dataList: MutableList<Any>
,这意味着您可以从列表读取和写入任何非空值。
我有这个片段:
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'
所以我必须投给如下的人:
val personList = (recyclerView.dataList as ArrayList<Person>)
personList.add( 0, Person("Lem Adane", "41 years old", 0))
因为 dataList 是 ArrayList<*> 而不是 ArrayList 并且 Kotlin 对此很严格。
Kotlin star-projections 不等同于 Java 的原始类型。 MutableList<*>
中的星号 (*) 表示您可以安全地从列表中读取值,但不能安全地将值写入其中,因为列表中的每个值都是某种未知类型(例如 Person
、String
、Number?
,或者可能 Any?
)。与 MutableList<out Any?>
.
相比之下,MutableList<Any?>
意味着您可以从列表中读取和写入任何值。这些值可以是相同类型(例如 Person
)或混合类型(例如 Person
和 String
)。
在您的情况下,您可能希望使用 dataList: MutableList<Any>
,这意味着您可以从列表读取和写入任何非空值。