Sunday 27 September 2015

Enumeration in Scala

In Scala, no special syntax for enumerations. Just define an object that extends the Enumeration class.

For example,

object WeekDay extends Enumeration {
     type WeekDay = Value
     val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
}
import WeekDay._

def isWorkingDay(d: WeekDay) = !(d == Sat || d == Sun)

WeekDay.values.filter(isWorkingDay)


WeekDay contains several values of type Value. Each declaration is actually calling a method named Value.
The type WeekDay is an alias that lets us reference WeekDay instead of Value.
It is used in isWorkingDay().

The id of each value is incremented and assigned automatically starting at 0, in declaration order.

By importing WeekDay._, it makes each enumeration value in scope.

Actually, enumerations are not used a lot in Scala. Instead, case classes are often used when "enumeration of values" is needed.


sealed trait Bread {val name: String}
case object doberman extends Bread {
  val name = "Doberman Pinscher"
}
case object yorkie extends Breed {
  val name = "Yorkshire Terrier"
}

Use enumerations when you just need "flags" with an index and optional user-friendly strings.
Use a sealed hierarchy of objects when they need to carry more state information.

No comments:

Post a Comment