投影类型为'ArrayList< *>'禁止使用"public open fun add(index:Int,element:E):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'

查看:312
本文介绍了投影类型为'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'

推荐答案

科特林星-projections 不等同于Java的原始类型. MutableList<*>中的星号(*)表示您可以安全地从列表中读取值,但是由于列表中的每个值都是某种未知类型(例如PersonStringNumber?,或者可能是Any?).与MutableList<out Any?>相同.

Kotlin star-projections are not equivalent to Java's raw types. The star (*) in MutableList<*> means that you can safely read values from the list but you cannot safely write values to it because the values in the list are each of some unknown type (e.g. Person, String, Number?, or possibly Any?). It is the same as MutableList<out Any?>.

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

In contrast, MutableList<Any?> means that you can read and write any value from and to the list. The values can be the same types (e.g. Person) or of mixed types (e.g. Person and String).

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

In your case you might want to use dataList: MutableList<Any> which means that you can read and write any non-null value from and to the list.

这篇关于投影类型为'ArrayList&lt; *&gt;'禁止使用"public open fun add(index:Int,element:E):java.util.ArrayList中定义的单元"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆