Sunday, August 23, 2009


Scala does not have a enum keyword like java so enumerations are not quite as smooth. Depending on your requirements there are two ways to make enumerations.

  1. Create an object that extends the Enumeration class
  2. Create a case-object hierarchy.
I present both ways. Here are some tips:
  • If you only need discrete and related values without custom behaviour create and object that extends Enumeration
  • If each value has custom information associated with it use case-objects

In the following examples notice the use of the sealed keyword when defining the abstract class MyEnum. Sealed specifies that the heirarchy is sealed. Only classes defined in the same file can extend the class.

Also notice in the case object example that the enumeration values are "case object" not "case class". The two are similar except that there is only one instance of a case object. However all the same boiler plate code is generated and you can still match in the same way.

  1. // Note: MyEnum is an object NOT a class
  2. scala>object MyEnum extends Enumeration("one", "two", "three") {
  3.      | type MyEnumType = Value
  4.      | val One, Two, Three = Value
  5.      | }
  6. defined module MyEnum
  7. scala> MyEnum.One
  8. res1: MyEnum.Value = one
  9. scala>def printEnum( value:MyEnum.MyEnumType ) = println( value.toString )
  10. printEnum: (MyEnum.MyEnumType)Unit
  11. scala> printEnum(MyEnum.Two)
  12. two
  13. // If you don't want to prefix enums with MyEnum. Then you
  14. // can import the values.  This is similar to static imports in java
  15. scala>import MyEnum._
  16. import MyEnum._
  17. scala>def printEnum( value:MyEnumType ) = println( value.toString )
  18. printEnum: (MyEnum.MyEnumType)Unit
  19. scala> printEnum(Three)
  20. three
  21. // Similar but with cases objects
  22. // Notice MyEnum is 'sealed' and the parameters have the 'val' keyword so they are public
  23. scala> abstract sealed class MyEnum(val name:String, val someNum:Int)
  24. defined class MyEnum
  25. scala>caseobject One extends MyEnum("one", 1)
  26. defined module One
  27. scala>caseobject Two extends MyEnum("two", 2)
  28. defined module Two
  29. scala>caseobject Three extends MyEnum("three", 3)
  30. defined module Three
  31. scala>def printEnum(value:MyEnum) = println(, value.someNum)
  32. printEnum: (MyEnum)Unit
  33. scala> printEnum(One)
  34. (one,1)

No comments:

Post a Comment