I have to say I don’t understand Scala enumeration classes. I can copy-paste the example from documentation, but I have no idea what is going on.
object WeekDay extends Enumeration {
type WeekDay = Value
val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
}
import WeekDay._
- What means
type WeekDay = Valueand why do I have to write that? - Why is
val Mon = Value? What does that even mean? - Why do I have to import the
WeekDay
object? And, - when I write
val day = WeekDay.Mon, why is it typeWeekDay.Value, not typeWeekDay?
the
Enumerationtrait has a type memberValuerepresenting the individual elements of the enumeration (it’s actually an inner class, but the difference doesn’t matter here).Thus
object WeekDayinherits that type member. The linetype WeekDay = Valueis just a type alias. It is useful, because after you import it elsewhere withimport WeekDay._, you can use that type, e.g.:Instead, a minimal version would just be:
and you do not have to import the contents of
object WeekDay, but then you would need to use typeWeekDay.Valueand to qualify individual members. So the example would becomeThe second question is about the meaning of
val Mon, ... = Value. This is indeed very confusing if you don’t look into the implementation ofEnumeration. This is not the assignment of a type! It is instead calling a protected method of the same name,Value, which returns a concrete instance of typeValue.It so happens that you can write
val a, b, c = fooin Scala, and for each valuea,b, andcthe methodfoowill be called again and again.Enumerationuses this trick to increment an internal counter so that each value is individual.If you open the Scala API docs for
Enumerationand click onVisibility: All, you will see that method appearing.