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?
The stack. pop() function in Scala returns the element that is available at the top of the stack and removes that element from the stack.
A stack is a last-in, first-out (LIFO) data structure. In most programming languages you add elements to a stack using a push method, and take elements off the stack with pop , and Scala is no different. Scala has both immutable and mutable versions of a stack, as well as an ArrayStack (discussed shortly).
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With