Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Scala Enumeration Value

As far as I can tell, Scala has definitions for the Enumeration Value class for Value(Int), Value(String), and Value(Int, String).

Does anyone know of an example for creating a new Value subclass to support a different constructor?

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.

Thanks.

like image 880
Ralph Avatar asked Mar 24 '10 11:03

Ralph


2 Answers

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
like image 57
Thomas Jung Avatar answered Oct 11 '22 03:10

Thomas Jung


Actually in Scala Enumeration has a much simpler meaning than in Java. For your purpose you don't have to subclass Enumeration nor its Value in any way, you just need to instantiate your own type in its companion object as a val. This way you'll get the familiar access model of val value:MyEnum = MyEnum.Value as you had in Java which is not possible in the example provided by Thomas Jung. There you'll have def value:My.MyVal = MyEnum.Value which is kinda confusing as it seems to me besides all the hackiness of the solution. Here's an example of what I propose:

class MyEnum(myParam:String)

object MyEnum {
  val Value1 = new MyEnum("any parameters you want")
  val Value2 = new MyEnum("")
  object Value3 extends MyEnum("A different approach to instantialization which also lets you extend the type in place")
}

Here you'll find a more complicated example: Scala Best Practices: Trait Inheritance vs Enumeration

like image 24
Nikita Volkov Avatar answered Oct 11 '22 04:10

Nikita Volkov