Overriding Scala Enumeration Value

后端 未结 4 875
孤街浪徒
孤街浪徒 2020-12-05 02:35

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

4条回答
  •  春和景丽
    2020-12-05 03:14

    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

提交回复
热议问题