Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.pop() equivalent in scala

Tags:

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?

like image 701
vaibhavbarmy Avatar asked Oct 07 '13 13:10

vaibhavbarmy


People also ask

What does .POP do in Scala?

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.

What is a stack in Scala?

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


1 Answers

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

like image 189
Shadowlands Avatar answered Oct 02 '22 21:10

Shadowlands