While enumerations are a built-in part of many programming languages, Scala takes a different route and implements them as an Enumeration
class in its standard library.
You just define an object
that extends the Enumeration
class and follow its idioms. So, at the byte code level, there is no connection between Scala enumerations
and the enum
constructs in Java.
package com.brown
/**
* Created by BrownWong on 2016/9/29.
*/
object Hello {
def main(args: Array[String]): Unit = {
println("ID\tBreed")
for (breed <- Breed.values) println(s"${breed.id}\t$breed")
}
}
object Breed extends Enumeration {
type Breed = Value
val doberman = Value("Doberman Pinscher")
val yorkie = Value("Yorkshire Terrier")
val scottie = Value("Scottish Terrier")
val dane = Value("Great Dane")
val portie = Value("Portuguese Water Dog")
}
output
ID Breed
0 Doberman Pinscher
1 Yorkshire Terrier
2 Scottish Terrier
3 Great Dane
4 Portuguese Water Dog
There are other overloaded versions of the Value
method. We’re using the one that takes a String
. Another one takes no arguments, so the string will just be the name of the value.
Here is the second example:
package com.brown
/**
* Created by BrownWong on 2016/9/29.
*/
object Hello {
import WeekDay._
def main(args: Array[String]): Unit = {
WeekDay.values filter isWorkingDay foreach println
}
def isWorkingDay(d: WeekDay) = !(d == Sat || d == Sun)
}
object WeekDay extends Enumeration {
type WeekDay = Value
val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
}
output
Mon
Tue
Wed
Thu
Fri
You don’t actually see enumerations
used a lot in Scala code, especially compared to Java code. They are lightweight, but they are also limited to the case where you know in advance the exact set of values to define. Clients can’t add more values.
Instead, case
classes are often used when an “enumeration of values” is needed. They are a bit more heavyweight, but they have two advantages:
- First, they offer greater flexibility to add methods and fields, and to use pattern matching on them.
- The second advantage is that they aren’t limited to a fixed set of known values. Client code can add more
case
classes to a base set that your library defines, when useful.
Ref