我有以下片段:

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'

推荐答案

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?>.

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).

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.

Kotlin相关问答推荐

文本正在被切断在200%的屏幕比例在Jetpack Compose

Kotlin中函数引用的否定

在Kotlin 有更好的结合方式?

如何让Gradle8+在编译Kotlin代码之前编译Groovy代码?然后把它们混合在一个项目中?

Kotlin多平台(KMP)保存到文件不能在iOS上保存

有没有一种简单的方法来识别物体?

如何将消费者放入 Kotlin 的 map 中?

Rabin-Karp字符串匹配的实现(Rolling hash)

按钮无法在 Android Studio 上打开新活动

修改器的属性是什么,我需要更改以使角变圆且宽度更小?喷气背包组合

在子类中覆盖 kotlin 运算符扩展函数

使用 Compose for Desktop Bundle 文件

为什么 KFunction2 在 Kotlin 中不是可表示类型?

错误:cannot find symbol import com.gourav.news.databinding.ActivityDetailBindingImpl;

runBlocking 中的 deferred.await() 抛出的异常即使在被捕获后也被视为未处理

无法在 kotlin android 中以编程方式禁用 EditText

runOnUiThread 没有调用

Ktor 在 java.library.path 中没有 netty_transport_native_epoll_x86_64

将ExpectedException与Kotlin一起使用

如何捕获传递给模拟函数的参数并返回它?