Can we get a `MutableList<T>.removeLast(coun...
# stdlib
b
Can we get a
MutableList<T>.removeLast(count: Int): List<T>
? 😄
1
d
Copy code
mutableListOf(1, 2, 3).dropLast(n)
b
Yeah, but drop doesn't actually remove items from the source list
d
Oh, I got what do you want
b
e
.subList(...).clear()
☝️ 2
b
How is sublist relevant here?
Doesn't it so return a new slice?
r
hmm, looks like subList is view of the list, via a backing field. Eg, any modifications on it, will reflect in parent list
Copy code
val list = mutableListOf(0, 1, 2, 4, 5)
list.subList(1, 3).add(3)

println(list)  // [0, 1, 2, 3, 4, 5]
👍 2
b
Ok, looks like this is the code required to approximate
removeLast(n)
Copy code
val input = mutableListOf(1,2,3)
mutableListOf().also{ out ->
  input.subList(input.size - n, input.size).also(out.addAll).clear()
}
e
surely this is easier?
Copy code
val input = mutableListOf(1, 2, 3)
val slice = input.subList(input.size - n, input.size)
slice.toMutableList().also { slice.clear() }
b
This is just semantics, the idea is the same.
d
What is the
slice.toMutableList()
part? That just creates a copy of the slice.
Copy code
val input = mutableListOf(1, 2, 3)
	input.subList(input.size - 2, input.size).clear()
    println(input)
prints [1]
Copy code
fun <T> MutableList<T>.removeLast(count: Int) {
    subList(size - count, size).clear()
}
r
Yeah, that copy is there on purpose: remove functions usually return what they removed. That last expression removes & returns a copy in one go
🧠 1