How to use Scala enums (Enumeration)

Problem: In Scala, you want to use something that works like a Java enum.


Extend the scala.Enumeration class to create your Scala enumeration:

package {

    object Margin extends Enumeration {
        type Margin = Value
        val TOP, BOTTOM, LEFT, RIGHT = Value


Then import the enumeration to use it in your application:

object Main extends App {


    // use an enumeration value in a test
    var currentMargin = TOP
    // later in the code ...
    if (currentMargin == TOP) println("working on Top")

    // print all the enumeration values
    Margin.values foreach println


Enumerations are useful tool for creating groups of constants, such as days of the week, months of the year, and many other situations where you have a group of related, constant values.

Using Scala traits as enums

You can also use the following approach of using a Scala trait to create the equivalent of a Java enum. Because it uses a “case object” approach it generates about four times as much code as an Enumeration, but depending on your needs it can also be a good approach:

// a "heavier" approach
package {
    sealed trait Margin
    case object TOP extends Margin
    case object RIGHT extends Margin
    case object BOTTOM extends Margin
    case object LEFT extends Margin

See also

The Scala Cookbook

If you found this tutorial helpful, you can find over 250 more examples in my book, the Scala Cookbook:

Scala Cookbook