vaibhavbarmy vaibhavbarmy - 4 months ago 48
Scala Question

.pop() equivalent in scala

I have worked on python
In python there is a function .pop() which delete the last value in a list and return that
deleted value
ex. x=[1,2,3,4]
x.pop() will return 4

I was wondering is there is a scala equivalent for this function?


If you just wish to retrieve the last value, you can call x.last. This won't remove the last element from the list, however, which is immutable. Instead, you can call x.init to obtain a list consisting of all elements in x except the last one - again, without actually changing x. So:

val lastEl = x.last
val rest = x.init

will give you the last element (lastEl), the list of all bar the last element (rest), and you still also have the original list (x).