Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

enums - Understanding scala enumerations

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 = Value and 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 type WeekDay.Value, not type WeekDay?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

the Enumeration trait has a type member Value representing the individual elements of the enumeration (it's actually an inner class, but the difference doesn't matter here).

Thus object WeekDay inherits that type member. The line type WeekDay = Value is just a type alias. It is useful, because after you import it elsewhere with import WeekDay._, you can use that type, e.g.:

def isWorkingDay(d: WeekDay) = ! (d == Sat || d == Sun)

Instead, a minimal version would just be:

object WeekDay extends Enumeration {
  val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
}

and you do not have to import the contents of object WeekDay, but then you would need to use type WeekDay.Value and to qualify individual members. So the example would become

def isWorkingDay(d: WeekDay.Value) = ! (d == WeekDay.Sat || d == WeekDay.Sun)

The second question is about the meaning of val Mon, ... = Value. This is indeed very confusing if you don't look into the implementation of Enumeration. 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 type Value.

It so happens that you can write val a, b, c = foo in Scala, and for each value a, b, and c the method foo will be called again and again. Enumeration uses this trick to increment an internal counter so that each value is individual.

If you open the Scala API docs for Enumeration and click on Visibility: All, you will see that method appearing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...