0

我正在使用 removeAt 函数,它工作正常,但突然编译器开始抛出错误未解决的参考:removeAt

这是代码:

fun main() {
 val nums = mutableListOf(-3, 167, 0, 9, 212, 3, 5, 665, 5, 8) // this is just a list
 var newList = nums.sorted() // this is the sorted list
 var finall = mutableListOf<Int>() // this is an empty list that will contain all the removed elements 
 for(i in 1..3) {
     var min: Int = newList.removeAt(0) // element removed from newList is saved from min variable
     // above line is producing the error 
     
     finall.add(min) // then the min variable is added to the empty list created before
     
 }
 
 println(finall)
 println(newList)

 
}

我研究了一堆文档,但我找不到我的错误

4

3 回答 3

2

对列表进行排序的第 3 行返回一个列表而不是 mutableList。所以 newList 是不可变的。用第三行替换var newList = nums.sorted().toMutableList()将使 newList 可变并解决您的问题。

于 2020-09-17T07:56:28.807 回答
2

的结果nums.sorted()是一个不可变列表,这意味着您无法更改它,或者换句话说,无法删除元素。

你需要告诉 kotlin 你想要一个可变列表var newList = nums.sorted().toMutableList()

于 2020-09-17T07:58:26.010 回答
0

因为newList是 List 对象。列表对象没有方法 removeAt

你需要使用newList.toMutableList().removeAt()

于 2020-09-17T08:01:19.737 回答