Often we have a variable that can take one of several values. For instance, a color field of an object could be either red, dark green, metallic orange, or black. In other languages such as C, Java, or Python, it is common to use a small integer to distinguish the possibilities.
In Scala, we let the compiler create one object for each possibility, and we use a reference to that object. Here is the somewhat strange syntax to do this:
object Color extends Enumeration { val Red, Green, Orange, Black = Value }You can then use the names Color.Red, Color.Green, Color.Orange, and Color.Black to denote the different possibilities. Each possibility is a unique object. The type of all these objects is Color.Value.
scala> var color = Color.Red color: Color.Value = Red scala> color = Color.Orange color: Color.Value = Orange
If you don't like the long names Color.Red etc., then you can use
import Color._and you can just use Red, Green, Orange, and Black instead:
scala> import Color._ scala> color = Black color: Color.Value = Black scala> var c = Green c: Color.Value = Green
If you don't like the funny name Color.Value for the type, you can define an alias for it:
scala> type Color = Color.Value defined type alias Color(It is customary to use the same name as for the enumeration singleton object above, but it is not necessary.)
Now you can use the type name Color for your fields and variables:
scala> var s: Color = Color.Red s: Color = Red scala> def orderCar(col: Color) { println("Ordering car in " + col) } orderCar: (col: Color)Unit scala> orderCar(Color.Black) Ordering car in Black scala> class Car(val color: Color) defined class Car scala> val sm3 = new Car(Color.Orange) sm3: Car = Car@1644028 scala> sm3.color res3: Color = Orange
As you have noticed, each enumeration object automatically has a toString method that prints a nice text. The same string can also be used to find an enumeration objects (that is, to convert from type String to type Color):
scala> val s = "Orange" s: java.lang.String = Orange scala> val c = Color.withName(s) c: Color.Value = Orange
The values of one enumeration are automatically assigned integer identifiers, and you can convert between enumeration object and integers:
scala> var c1 = Red c1: Color.Value = Red scala> c1.id res0: Int = 0 scala> Green.id res1: Int = 1 scala> Black.id res2: Int = 3 scala> Color(2) res3: Color.Value = Orange