What is stack.push() in Scala?

The stack.push() function in Scala is used to insert an element at the top of the stack.

The following illustration shows a visual representation of the stack.push() function.

Visual representation of stack.push() function

The scala.collection.mutable.Stack module is required in order to use stack.push().

Syntax

stack_name.push(element)
//where stack_name is name of the stack

Parameters

This function requires an element as a parameter.

Return value

The stack.push() function inserts an element sent as a parameter at the top of the stack.

Code

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

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