理解Scala枚举 [英] Understanding scala enumerations
问题描述
我不得不说我不懂 Scala 枚举类.我可以从文档中复制粘贴示例,但我不知道发生了什么.
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._
type WeekDay = Value
是什么意思,我为什么要写这个?- 为什么
val Mon = Value
?这到底是什么意思? - 为什么我必须导入
WeekDay
目的?而且, - 当我写
val day = WeekDay.Mon
时,为什么输入的是WeekDay.Value
,而不是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 typeWeekDay.Value
, not typeWeekDay
?
推荐答案
Enumeration
trait 有一个类型成员 Value
表示枚举的各个元素(它实际上是一个内部类,但这里的区别并不重要).
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).
因此 object WeekDay
继承了该类型成员.type WeekDay = Value
行只是一个类型别名.它很有用,因为在你用 import WeekDay._
将它导入到别处之后,你可以使用那个类型,例如:
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)
相反,最小版本将是:
object WeekDay extends Enumeration {
val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
}
并且您不必必须导入object WeekDay
的内容,但是您需要使用类型WeekDay.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)
<小时>
第二个问题是关于val Mon, ... = Value
的含义.如果你不研究 Enumeration
的实现,这确实很令人困惑.这不是类型的赋值!相反,它调用了一个受保护的同名方法,Value
,它返回一个 Value
类型的具体实例.
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
.
碰巧您可以在 Scala 中编写 val a, b, c = foo
,并且对于每个值 a
, b
,并且 c
方法 foo
将被一次又一次地调用.Enumeration
使用这个技巧来增加一个内部计数器,以便每个值都是独立的.
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.
如果您打开 Enumeration
的 Scala API 文档并单击 Visibility: All
,您将看到该方法出现.
If you open the Scala API docs for Enumeration
and click on Visibility: All
, you will see that method appearing.
这篇关于理解Scala枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!