Newer
Older
We have seen that classes can *aggregate several values* into a single abstraction.
For instance, the `Rational` class aggregates a numerator and a denominator.
Conversely, how could we define an abstraction *accepting alternative values*?
Define a `Color` type with values `Red`, `Green`, `Blue`, and `Magenta`.
~~~
trait Color
object Red extends Color
object Green extends Color
object Blue extends Color
object Magenta extends Color
~~~
As a simpler and shorter alternative, we
can define a type with its values in an \red{enum}:
- A new \red{type}, named `Color`.
- Four possible \red{values} for this type, `Color.Red`, `Color.Green`, `Color.Blue`, and
`Color.Magenta`.
Enumerate the Values of an Enumeration
======================================
It is possible to enumerate all the values of an enum by calling the
`values` operation on the enum companion object:
\begin{tabular}{ll}
\verb@Color.values@ \wsf Array(Red, Green, Blue, Magenta) \\
\verb@val c = Color.Green@ \wsf c: Color = Green \\
Discriminate the Values of an Enumeration
=========================================
You can discriminate between the values of an enum by using a \red{match}
expression:
~~~
import Color._
def isPrimary(color: Color): Boolean =
color match
case Red | Green | Blue => true
case Magenta => false
~~~
- `match` is followed by a sequence of \red{cases}, `case value => expr`.
- Each case associates an \red{expression} `expr` with a
\red{constant} `value`.
- Default cases are written with an underscore, e.g.
case Magenta => false
case _ => true
~~~
We will see later that pattern matching can do more
than discriminating enums.
Enumerations Can Take Parameters
================================
case Unicycle extends Vehicle(1)
case Bicycle extends Vehicle(2)
case Car extends Vehicle(4)
~~~
- Enumeration cases that pass parameters have to use an explicit `extends` clause
Enumerations Are Shorthands for Classes and Objects
===================================================
The `Color` enum is expanded by the Scala compiler to roughly the following
structure:
val Red = Color()
val Green = Color()
val Blue = Color()
val Magenta = Color()
...
~~~
(in reality, there are some more methods defined)