The key in List<T>.slice
function is the .toList()
at the end, which will create a new List with the elements, using a shallow element copy.
For summary:
.slice()
will create a new List with the shallow copy of the subset of elements; if the original list contains objects, changes to values within the objects will be seen in the slice, but the replacement of an object or scalar in the original list will not be seen in the slice.subList()
is only a view of the original List, which will reflect changes to both the objects/scalars in the list as well as changes to the values within the objects in the list
You can see differences here: https://pl.kotl.in/-JU8BDNZN
fun main() {
val myList = mutableListOf(1, 2, 3, 4)
val subList = myList.subList(1, 3)
val sliceList = myList.slice(1..2)
println(subList) // [2, 3]
println(sliceList) // [2, 3]
myList[1] = 5
println(subList) // [5, 3]
println(sliceList) // [2, 3]
}