gpt4 book ai didi

collections - Kotlin 的列表缺少 "add"、 "remove"、 map 缺少 "put"等?

转载 作者:IT老高 更新时间:2023-10-28 13:25:55 27 4
gpt4 key购买 nike

在 Java 中,我们可以执行以下操作

public class TempClass {
List<Integer> myList = null;
void doSomething() {
myList = new ArrayList<>();
myList.add(10);
myList.remove(10);
}
}

但是如果我们像下面这样直接重写成Kotlin

class TempClass {
var myList: List<Int>? = null
fun doSomething() {
myList = ArrayList<Int>()
myList!!.add(10)
myList!!.remove(10)
}
}

我收到了未从我的列表中找到 addremove 函数的错误

我解决了将它转换为 ArrayList 的工作,但需要转换它很奇怪,而在 Java 中则不需要转换。这违背了拥有抽象类 List 的目的

class TempClass {
var myList: List<Int>? = null
fun doSomething() {
myList = ArrayList<Int>()
(myList!! as ArrayList).add(10)
(myList!! as ArrayList).remove(10)
}
}

有没有办法让我使用 List 但不需要强制转换,就像在 Java 中可以做的那样?

最佳答案

Unlike many languages, Kotlin distinguishes between mutable and immutable collections (lists, sets, maps, etc). Precise control over exactly when collections can be edited is useful for eliminating bugs, and for designing good APIs.

https://kotlinlang.org/docs/reference/collections.html

您需要使用 MutableList列表。

class TempClass {
var myList: MutableList<Int> = mutableListOf<Int>()
fun doSomething() {
// myList = ArrayList<Int>() // initializer is redundant
myList.add(10)
myList.remove(10)
}
}

MutableList<Int> = arrayListOf()应该也可以。

关于collections - Kotlin 的列表缺少 "add"、 "remove"、 map 缺少 "put"等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37913252/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com