Kotlin的名单缺少“添加”,“删除”等?

在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) } } 

有没有办法让我使用列表,但不需要投它,像什么可以在Java中做?

与许多语言不同,Kotlin区分了可变集合和不可变集合(列表,集合,映射等)。 精确控制集合何时编辑对于消除错误和设计良好的API非常有用。

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()也应该工作。

显然Kotlin的默认列表是不可变的。 要有一个List可以改变,应该使用MutableList如下

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

更新尽管如此,不建议使用MutableList,除非您真的想要更改列表。 请参阅https://hackernoon.com/read-only-collection-in-kotlin-leads-to-better-coding-40cdfa4c6359了解只读集合如何提供更好的编码&#x3002;

在不可变数据的概念中,也许这是一个更好的方法:

 class TempClass { val list: List<Int> by lazy { listOf<Int>() } fun doSomething() { list += 10 list -= 10 } }