我正在使用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)
 
}我研究了一大堆文档,但我找不到我的错误
发布于 2020-09-17 15:56:29
第三行是对列表进行排序的地方,它返回一个列表而不是mutableList。所以newList是不可变的。将第三行替换为var newList = nums.sorted().toMutableList()将使newList变得可变,并解决您的问题。
发布于 2020-09-17 15:58:26
nums.sorted()的结果是一个不可变的列表,这意味着您不能更改它,换句话说,不能删除元素。
你需要告诉kotlin你想要一个可变列表var newList = nums.sorted().toMutableList()
发布于 2020-09-17 16:01:20
因为newList是列表对象。List object无方法removeAt
您需要使用newList.toMutableList().removeAt()
https://stackoverflow.com/questions/63933484
复制相似问题