Problem: In Scala, you want to use something that works like a Java enum
.
Solution
Extend the scala.Enumeration class to create your Scala enumeration:
package com.acme.app { 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 { import com.acme.app.Margin._ // 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 import com.acme.app.Margin 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 com.acme.app { 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: