Home > Blockchain >  How to implement enums with values in Scala 2.12.15
How to implement enums with values in Scala 2.12.15

Time:02-22

In Java, one can use (from https://www.baeldung.com/java-enum-values#adding-constructor)

public enum Element {
    H("Hydrogen"),
    HE("Helium"),
    NE("Neon");

    public final String label;

    private Element(String label) {
        this.label = label;
    }
}

to construct Enums with string values, such that NE.label would yield "Neon".

How do you do the same thing, but in Scala version 2.12.15? (Please show the above example translated to Scala)

CodePudding user response:

The best way to create enums in Scala is through a basic ADT like this:

sealed abstract class Element(val label: String)
object Element {
  final case object H extends Element(label = "Hydrogen")
  final case object HE extends Element(label = "Helium")
  final case object NE extends Element(label = "Neon")
}

If you want some goodies, like getting the list of all elements or a getByName method, for free.
Then the best would be to combine the above with the Enumeratum library.

  • Related