vaibhavbarmy vaibhavbarmy - 3 years ago 180
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?

Answer Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download