11.28. Using a Stack

Problem

You want to use a stack data structure in a Scala application.

Solution

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). The following examples demonstrate how to use the mutable Stack class.

Create an empty, mutable stack of any data type:

import scala.collection.mutable.Stack
var ints = Stack[Int]()
var fruits = Stack[String]()

case class Person(var name: String)
var people = Stack[Person]()

You can also populate a stack with initial elements when you create it:

val ints = Stack(1, 2, 3)

Once you have a mutable stack, push elements onto the stack with push:

// create a stack
scala> var fruits = Stack[String]()
fruits: scala.collection.mutable.Stack[String] = Stack()

// add one element at a time
scala> fruits.push("apple")
res0: scala.collection.mutable.Stack[String] = Stack(apple)

scala> fruits.push("banana")
res1: scala.collection.mutable.Stack[String] = Stack(banana, apple)

// add multiple elements
scala> fruits.push("coconut", "orange", "pineapple")
res2: scala.collection.mutable.Stack[String] =
  Stack(pineapple, orange, coconut, banana, apple)

To take elements off the stack, pop them off the top of the stack:

scala> val next = fruits.pop
next: String = pineapple

scala> fruits res3: scala.collection.mutable.Stack[String] ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.