更新列表Kotlin中的对象



我正在尝试修改allVehicles变量,因此它应该包含vehiclesWithProblems列表中的problem信息。

这是我的代码的简化版本,但我需要一个更新的allVehicles列表,其中包含replacement并删除旧的(没有problem的(。

我怎样才能做到这一点?此代码不起作用,allVehicles列表保持不变。

data class VehicleContainer(
val id: Int,
val vehicles: List<Vehicle>
)
data class Vehicle(
val id: Int,
val name: String,
val problem: Problem
)
data class Problem(
val quantity: Int,
val problemList: List<Int>,
val info: String? = ""
)
fun main() {
val vehiclesWithProblems = listOf<Vehicle>() //list of vehicles with problems - wont be empty
val allVehicles = mutableListOf<Vehicle>()//list of all vehicles (initially without any problems, but won't be empty either)
allVehicles.forEachIndexed { index, vehicle ->
val newVehicle = vehiclesWithProblems.find { vehicleWithProblem -> vehicle.id == vehicleWithProblem.id }
if (newVehicle != null) {
val replacement = vehicle.copy(problem = Problem(
quantity = newVehicle.problem.quantity,
problemList = newVehicle.problem.problemList,
info = newVehicle.problem.info)
)
allVehicles[index] = replacement
}
}
}

在我看来,allVehicles列表实际上被修改了,但要小心!您制作了一份车辆的副本,其中只有问题发生了变化,其余部分保持不变。运行下面的代码,你会看到循环后,«特斯拉没有问题»仍然在列表中,但现在有问题(所以列表实际上更改的。(:

fun main() {
val vehiclesWithProblems = listOf(Vehicle(1, "Tesla", Problem(1, listOf(1), "Problem #1"))) //list of vehicles with problems - wont be empty
val allVehicles = mutableListOf(Vehicle(1, "Tesla without a problem", Problem(0, listOf(0), "No problem")))//list of all vehicles (initially without any problems, but won't be empty either)
println("vehiclesWithProblems: $vehiclesWithProblems")
println("allVehicles: $allVehicles")
allVehicles.forEachIndexed { index, vehicle ->
val newVehicle = vehiclesWithProblems.find { vehicleWithProblem -> vehicle.id == vehicleWithProblem.id }
if (newVehicle != null) {
val replacement = vehicle.copy(problem = Problem(
quantity = newVehicle.problem.quantity,
problemList = newVehicle.problem.problemList,
info = newVehicle.problem.info)
)
println("Changing #$index!")
allVehicles[index] = replacement
}
}
println("After the loop, allVehicles: $allVehicles")
}

最新更新