Creating a Java Enum in Scala

前端 未结 4 1896
执笔经年
执笔经年 2020-12-14 09:59

My workplace has been experimenting in moving from Java to Scala for some tasks, and it works well for what we\'re doing. However, some preexisting logging methods expect a

4条回答
  •  失恋的感觉
    2020-12-14 10:31

    Whilst it's probably not a good idea (see other posts for actual good ideas), it is possible to extend java.lang.Enum in Scala. Your code would have worked, if you'd put both the class and its companion object in the same compilation unit (in the REPL, each statement is executed in its own compilation unit, unless you use :paste mode).

    If you use :paste mode, and paste in the following code, Scala will happily compile it:

    sealed class AnEnum protected(name: String, ordinal: Int) extends java.lang.Enum[AnEnum](name, ordinal)
    object AnEnum {
      val ENUM1 = new AnEnum("ENUM1",0)
      case object ENUM2 extends AnEnum("ENUM2", 1) // both vals and objects are possible
    }
    

    However, Java interop will probably not be satisfactory. The Java compiler adds static values and valueOf methods to new enum classes, and ensures that the names and ordinals are correct, which Scala will not.

    Even if you take these steps yourselves, Java won't trust your enum because the class doesn't have the ENUM modifier. This means that Class::isEnum will say your class isn't an enum, which will affect the static Enum::valueOf method, for example. Java's switch statement won't work with them either (although Scala's pattern matching should work, if the enum values are case objects).

提交回复
热议问题