Creating Enumerations

In Scala you can use Java enums. Alternately, you can create enumerations in Scala as well.

To create an enumeration in Scala you will start by creating an object—much like the syntax used to create a singleton. However, you can assign multiple named instances—after all, the singleton pattern doesn’t force a single instance; it’s simply a way to control the creation of select instances.

Let’s create an enumeration to represent various currencies:

WorkingWithObjects/finance1/finance/currencies/Currency.scala
 
package​ finance.currencies
 
 
object​ Currency ​extends​ Enumeration {
 
type​ Currency = Value
 
val​ CNY, GBP, INR, JPY, NOK, PLN, SEK, USD = Value
 
}

An enumeration is an object that extends the Enumeration ...

Get Pragmatic Scala 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.