【问题标题】:Out-projected type 'ArrayList<*>' prohibits the use of 'public open fun add(index: Int, element: E): Unit defined in java.util.ArrayList'Out-projected type 'ArrayList<*>' 禁止使用'public open fun add(index: Int, element: E): Unit defined in java.util.ArrayList'
【发布时间】:2019-11-06 17:15:15
【问题描述】:

我有这个sn-ps:

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'

【问题讨论】:

    标签: generics kotlin kotlin-android-extensions kotlin-extension


    【解决方案1】:

    Kotlin star-projections 不等同于 Java 的原始类型。 MutableList&lt;*&gt; 中的星号 (*) 表示您可以安全地从列表中读取值,但不能安全地向其写入值,因为列表中的值都是某种未知类型(例如 PersonString、@ 987654325@,或者可能是Any?)。与MutableList&lt;out Any?&gt;相同。

    相比之下,MutableList&lt;Any?&gt; 意味着您可以从列表中读取和写入任何值。这些值可以是相同类型(例如Person)或混合类型(例如PersonString)。

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-29
        • 1970-01-01
        • 2017-12-26
        • 2016-12-31
        • 1970-01-01
        • 2022-12-19
        • 1970-01-01
        相关资源
        最近更新 更多