开发者

How to extend existing enumerations objects in Scala?

I'm wondering if you can extend already existing enumerations in Scala. For example:

object BasicAnimal extends Enumeration{
    type BasicAnimal = Value
    val Cat, Dog = Value   
}
开发者_StackOverflow社区

Can this be extended something like this:

object FourLeggedAnimal extends BasicAnimal{
    type FourLeggedAnimal = Value
    val Dragon = Value
}

Then, the elements in FourLeggedAnimal would be Cat, Dog and Dragon. Can this be done?


No, you cannot do this. The identifier BasicAnimal after extends is not a type, it is a value, so it won't work, unfortunately.


May be that's the way:

object E1 extends Enumeration {
    type E1 = Value
    val A, B, C = Value
}
class ExtEnum(srcEnum: Enumeration) extends Enumeration {
    srcEnum.values.foreach(v => Value(v.id, v.toString))
}
object E2 extends ExtEnum(E1) {
    type E2 = Value
    val D, E = Value
}
println(E2.values) // prints > E2.ValueSet(A, B, C, D, E)

One remark: it's not possible to use E1 values from E2 by name:

E2.A // Can not resolve symbol A

But you can call them like:

E2(0) // A

or:

E2.withName(E1.A.toString) // A
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜