Enumerations in ScalaSaturday, January 31st, 2009 with 3 Comments »

I’ve been looking at how to do enumerations in Scala, and there seems to be two popular methods: extending Enumeration and the use of case classes. The following are some examples…

Method 1: Extending Enumeration
Example:

object Animal extends Enumeration {
  val DOG, CAT, FISH, TURTLE = Value
}

Usage:

val a = Animal.DOG
if (a == Animal.DOG) println(":)")

This is nice and simple, and does the job when the enumerated values are intended to be simple and functionless.

However, what if you wanted Animals to have their own functionality, rather than just being an identifier?  Scala’s more flexible method of enumeration could be used…

Method 2: Case Classes
Lets say we wanted to make the animals make a sound:

abstract class Animal {
  def sound() : Any = throw new Exception("This animal does not make "
                                          + "a sound!")
}
case object DOG extends Animal() {
  override def sound() = println("wuuf.")
}
case object CAT extends Animal() {
  override def sound() = println("RAWR!")
}
case object FISH extends Animal()
case object TURTLE extends Animal()

Usage:

val a : Animal = CAT
a.sound()

val b : Animal = TURTLE
b.sound() // this will throw an exception

// can also be used in case statements
val output = a match {
  case CAT => "Hello thar kitteh!"
  case DOG => "Hello thar dawg!"
  case _ => "Hello thar... er... you're not a kitteh nor a dawg :| "
}

You can also do something very interesting things within the case statement, like decomposing the object’s attributes (you’ll need to scroll down a bit to find it).  The backfire to using this method over the Enumeration class is that, unlike Enumeration’s filter() and foreach() capability, you can’t seem to easily list out all the classes that extend the Animal class.

Get updates as often as we post! Subscribe to our full feed or comments feed.