Skip to content

Enum extends another enum #4961

Closed
Closed
@skvithalani

Description

@skvithalani

We are currently using Enumeratum library to have enums in our code base. In a particular use case, we have a requirement such as there is inheritance in the behavior of enums for e.g.

sealed abstract class FullAlarmSeverity private[alarm] (val level: Int, val latchable: Boolean) extends EnumEntry with Lowercase {

  /**
   * The name of SeverityLevels e.g. for Major severity level, the name will be represented as `major`
   */
  def name: String = entryName

  def >(otherSeverity: FullAlarmSeverity): Boolean = this.level > otherSeverity.level

  def max(otherSeverity: FullAlarmSeverity): FullAlarmSeverity = if (otherSeverity > this) otherSeverity else this

  def isHighRisk: Boolean = this.level > 0
}

object FullAlarmSeverity extends Enum[FullAlarmSeverity] {

  /**
   * Returns a sequence of all alarm severity
   */
  def values: IndexedSeq[FullAlarmSeverity] = findValues ++ AlarmSeverity.values

  case object Disconnected extends FullAlarmSeverity(4, false)
}

sealed abstract class AlarmSeverity private[alarm] (override val level: Int, override val latchable: Boolean)
    extends FullAlarmSeverity(level, latchable)

object AlarmSeverity extends Enum[AlarmSeverity] {

  /**
   * Returns a sequence of all alarm severity
   */
  def values: IndexedSeq[AlarmSeverity] = findValues

  case object Okay          extends AlarmSeverity(0, false)
  case object Warning       extends AlarmSeverity(1, true)
  case object Major         extends AlarmSeverity(2, true)
  case object Indeterminate extends AlarmSeverity(3, true)
  case object Critical      extends AlarmSeverity(5, true)

As one would have noticed in the above code, FullAlarmSeverity companion object has values manipulated to also append the AlarmSeverity values, so that Okay from AlarmSeverity can also be deserialized to FullAlarmSeverity.

Using enums instead of ADT gives us the advantage of using withName and values methods. But trying to achieve something similar with Dotty seems pretty difficult.

So, is there any way to do so in Dotty with Enum or is there any other pattern that can give us the same effect of inheritance along with the advantage of withName and values methods from Enumeratum ?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions