覆盖Scala枚举值 [英] Overriding Scala Enumeration Value
问题描述
据我所知,Scala为Enumeration Value类定义了Value(Int),Value(String)和Value(Int,String)。
As far as I can tell, Scala has definitions for the Enumeration Value class for Value(Int), Value(String), and Value(Int, String).
有人知道创建新的Value子类以支持其他构造函数的示例吗?
Does anyone know of an example for creating a new Value subclass to support a different constructor?
例如,如果我想创建一个Value(Int, String,String)对象,我该怎么办?我想要使用Enumeration类的所有其他好处。
For example, If I want to create an Enumeration with Value(Int, String, String) objects, how would I do it? I would like all of the other benefits of using the Enumeration class.
谢谢。
推荐答案
Enumeration值是Val类的实例。可以扩展此类,并且可以添加工厂方法。
The Enumeration values are instance of the Val class. This class can be extended and a factory method can be added.
object My extends Enumeration {
val A = Value("name", "x")
val B = Value("other", "y")
class MyVal(name: String, val x : String) extends Val(nextId, name)
protected final def Value(name: String, x : String): MyVal = new MyVal(name, x)
}
scala> My.B.id
res0: Int = 1
scala> My.B.x
res1: String = y
这篇关于覆盖Scala枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!