Learn How To Create And Use Enumerations (enum)

By Nadim Bahadoor | Last updated: February 24, 2020 at 12:32 pm

Overview

In this tutorial, we will go over how to create and use enumerations in Scala.

 

If you have used Java or .NET in the past, I'm pretty sure that you have used the enum keyword to define your enumerations.

 

But in Scala there is no enum keyword. Instead, Scala provides an Enumeration class which you can extend in order to create your enumerations.

Steps

1. How to create an Enumeration
Let us extend the Enumeration class and create an enumeration to represent donuts.


println("Step 1: How to create an enumeration")
object Donut extends Enumeration {
  type Donut = Value

  val Glazed      = Value("Glazed")
  val Strawberry  = Value("Strawberry")
  val Plain       = Value("Plain")
  val Vanilla     = Value("Vanilla")
}

2. How to print the String value of the enumeration
Now that we've created our Donut enumeration in Step 1, suppose you would like to print the String value for the Vanilla element.


println("\nStep 2: How to print the String value of the enumeration")
println(s"Vanilla Donut string value = ${Donut.Vanilla}")

You should see the following output when you run your Scala application in IntelliJ:


Step 2: How to print the String value of the enumeration
Vanilla Donut string value = Vanilla

3. How to print the id of the enumeration

Similar to Step 2, you first need to navigate down to the Vanilla element and then call the id function.


println("\nStep 3: How to print the id of the enumeration")
println(s"Vanilla Donut's id = ${Donut.Vanilla.id}")

You should see the following output when you run your Scala application in IntelliJ:


Step 3: How to print the id of the enumeration
Vanilla Donut's id = 3

NOTE:

  • But where did this magic id function come from?
  • If you recall from Step 1, you extended the Enumeration class. As a result, the Donut enumeration inherited a bunch of useful functions with the id function being one of them.

4. How to print all the values listed in Enumeration

What if you wanted to print all the values that are defined for the Donut enumeration?

 

Very easy! You simply need to call the values function on the Donut enumeration.


println("\nStep 4: How to print all the values listed in Enumeration")
println(s"Donut types = ${Donut.values}")

You should see the following output when you run your Scala application in IntelliJ:


Step 4: How to print all the values listed in Enumeration
Donut types = Donut.ValueSet(Glazed, Strawberry, Plain, Vanilla)

5. How to pattern match on enumeration values

Let's use what you've learned from the Pattern Matching tutorial, and find our favourite donuts namely Strawberry and Glazed :)


println("\nStep 5: How to pattern match on enumeration values")
Donut.values.foreach {
  case d if (d == Donut.Strawberry || d == Donut.Glazed) => println(s"Found favourite donut = $d")
  case _ => None
}

You should see the following output when you run your Scala application in IntelliJ:


Step 5: How to pattern match on enumeration values
Found favourite donut = Glazed
Found favourite donut = Strawberry

6. How to change the default ordering of enumeration values

Suppose you would like to change the default ordering of the enumeration values.

 

When you declare your enumeration elements, you can pass in the index as a parameter to the Value type.


println("\nStep 6: How to change the default ordering of enumeration values")
object DonutTaste extends Enumeration{
  type DonutTaste = Value

  val Tasty       = Value(0, "Tasty")
  val VeryTasty   = Value(1, "Very Tasty")
  val Ok          = Value(-1, "Ok")
}

println(s"Donut taste values = ${DonutTaste.values}")
println(s"Donut taste of OK id = ${DonutTaste.Ok.id}")

You should see the following output when you run your Scala application in IntelliJ:


Step 6: How to change the default ordering of enumeration values
Donut taste values = DonutTaste.ValueSet(Ok, Tasty, Very Tasty)
Donut taste of OK id = -1

NOTE:

  • The Ok element was moved to the front of the enumeration values.

This concludes our tutorial on Learn How To Create And Use Enumerations (enum) and I hope you've found it useful!

 

Stay in touch via Facebook and Twitter for upcoming tutorials!

 

Don't forget to like and share this page :)

Summary

In this tutorial, we went over the following:

  • How to create an Enumeration
  • How to print the String value of an Enumeration
  • How to print the id of an Enumeration
  • How to print all the values listed in an Enumeration
  • How to use pattern matching to find specific Enumeration
  • How to change the ordering of Enumeration

Tip

Source Code

The source code is available on the allaboutscala GitHub repository.

What's Next

 

In the next tutorial, we look a bit further into defining Algebraic Data Types (ADT), and look ahead to Scala 3 with the new enum keyword.

Nadim Bahadoor on FacebookNadim Bahadoor on GithubNadim Bahadoor on LinkedinNadim Bahadoor on Twitter
Nadim Bahadoor
Technology and Finance Consultant with over 14 years of hands-on experience building large scale systems in the Financial (Electronic Trading Platforms), Risk, Insurance and Life Science sectors. I am self-driven and passionate about Finance, Distributed Systems, Functional Programming, Big Data, Semantic Data (Graph) and Machine Learning.
Other allaboutscala.com tutorials you may like: