What is stack.size() in Scala?

The Stack.size function in Scala returns the number of elements in a Stack object. In short, this function is used to get the current size of the Stack object.

The following illustration shows a visual representation of the Stack.size function.

A visual representation of the Stack.size function

To use the Stack.size function, you must include the following module:

scala.collection.mutable.Stack

Syntax

stack_name.size;
// where the stack_name is the name of the stack object

Parameter

The Stack.size function does not require any parameters.

Return value

This function returns the number of elements in the Stack object.

Code

The following code shows how to use the Stack.size 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);
println("The following are the elements in the stack: " + stack);
println("The following is the size of the stack: " + stack.size);
}

Explanation

The push() method is first used to add values to the object stack. The size() method in line 1111 returns the number of elements in the object stack.

Free Resources