What is stack.pop() 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.

Figure 1 shows the visual representation of the stack.pop() function.

Figure 1: Visual representation of the stack.pop() function

The following module is required in order to use the function: scala.collection.mutable.Stack

Syntax


stack_name.pop();
// where the stack_name is the name of the stack

Parameters

This function does not require a parameter.

Return value

This function returns the element available at the top of the stack and removes that element from the stack.

Code

The following code shows how to use the stack.pop() function.

import scala.collection.mutable.Stack
object Main extends App {
var stack = Stack[Int]()
stack.push(0);
stack.push(2);
stack.push(5);
stack.push(3);
stack.push(1);
//Stack before removing
println("Following are the elements in Stack before removing: " + stack);
//Stack after removing
println("The element removed from the front of Stack: "+stack.pop());
println("Following are the elements in Stack after removing: " + stack);
}

Free Resources