【问题标题】:Kotlin ArrayList returns data type when removeAt called调用 removeAt 时 Kotlin ArrayList 返回数据类型
【发布时间】:2020-11-09 13:54:38
【问题描述】:

我有一个 Kotlin ArrayList,其中包含一个名为 TaskModel 的数据类(例如 val taskModelList = ArrayList<TaskModel>()

但是当我像 val taskModelList2 = taskModelList.removeAt(1) 一样调用 remove 时,它​​返回 t 作为类型 TaskModel 而不是 ArrayList<TaskModel>。如何让它返回 TaskModel 的 ArrayList?

【问题讨论】:

  • 为什么不能继续使用taskModelList
  • 为什么会返回一个ArrayList?您正在删除 1 项。你得到了删除的项目

标签: android kotlin arraylist data-class


【解决方案1】:

这是预期的行为。删除的项目将被退回 (ArrayList),您可以将原始列表与剩余项目一起使用。无需重新分配列表。

【讨论】:

    【解决方案2】:

    如果您想找回列表,可以使用filterIndexed

    taskModelList.filterIndexed { index, _ -> index != 1 }
    

    【讨论】:

      【解决方案3】:

      你可以使用apply():

      fun main() {
          arrayListOf("a", "remove", "me", "b", "c")
              .apply { removeAt(1) }
              .apply { removeAt(1) }
              .also(::println)
      }
      

      输出:

      [a, b, c]
      

      【讨论】:

        猜你喜欢
        • 2014-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-05
        • 1970-01-01
        相关资源
        最近更新 更多