`scala.Enumeration$Value` 中的 `toString` 是如何实现的?
我有一个枚举 Fruit
定义为:
object Fruit extends Enumeration {
val Apple, Banana, Cherry = Value
}
现在在 Scala 2.7.x 上打印此枚举的值给出:
scala> Fruit foreach println
line1$object$$iw$$iw$Fruit(0)
line1$object$$iw$$iw$Fruit(1)
line1$object$$iw$$iw$Fruit(2)
但是 Scala 2.8 上的相同操作给出:
scala> Fruit foreach println
warning: there were deprecation warnings; re-run with -deprecation for details
Apple
Banana
Cherry
我的问题是:
方法 toString 是怎样的Scala 2.8 中的
实现了吗?我尝试查看 Enumeration
中的Enumeration
的来源,但无法理解任何内容。
I have an enum Fruit
defined as:
object Fruit extends Enumeration {
val Apple, Banana, Cherry = Value
}
Now printing values of this enum, on Scala 2.7.x gives:
scala> Fruit foreach println
line1$object$iw$iw$Fruit(0)
line1$object$iw$iw$Fruit(1)
line1$object$iw$iw$Fruit(2)
However the same operation on Scala 2.8 gives:
scala> Fruit foreach println
warning: there were deprecation warnings; re-run with -deprecation for details
Apple
Banana
Cherry
My question is:
How is the method toString
in Enumeration
in Scala 2.8 implemented? I tried looking into the source of Enumeration
but couldn't understand anything.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Scala 2.8.0.RC2 中,您可以在
Enumeration.scala
的第 273 行。Val
的实例通过 第 192 行。目前我不明白如何提取名称(Apple、Banana、...
)。有人可以帮忙吗?In Scala 2.8.0.RC2 you can find the implementation of
toString
in the inner classVal
in line 273 ofEnumeration.scala
. The instances ofVal
are instantiated through theValue
method in line 192. Currently I don't understand how the names (Apple, Banana, ...
) are extracted. May somebody can help out?该实现基于Java反射API。
如果为枚举值定义 val:
Fruit 类中有用于 val 的方法:
如果名称未明确显示,
toString
会调用Enumeration.this.nameOf(i)
放。此方法将尝试查找返回Value
实例的枚举类中的所有方法。这些是 Fruit 类的方法。
然后,它使用方法的名称和枚举值的 id 来构建映射
id -> name
并使用枚举值的 id 从地图中检索名称。如果您定义这样的枚举,则此实现很容易被破坏:
This Fruit.value 返回
object$Fruit.ValueSet(x, B, C)
而不是object$Fruit.ValueSet(A, B,C)
。The implementation is based on the Java reflection API.
If you define val for the enum values:
There are methods for the val in the class Fruit:
toString
callsEnumeration.this.nameOf(i)
if the name is not explicitly set. This method will try to find all methods in the enumeration class returningValue
instances.These are the methods of the Fruit class.
It then takes the name of the methods and the ids of enum values to build a map
id -> name
and retrieves the name from the map with the id of enum value.This implementation can be easily broken if you define a enum like this:
This Fruit.value returns
object$Fruit.ValueSet(x, B, C)
notobject$Fruit.ValueSet(A, B, C)
.