Enumerations in Scala with multiple constructor options

I am writing my first big Scala program. In the Java equivalent, I have an enumeration that contains labels and tooltips for my user interface controls:

public enum ControlText {
  CANCEL_BUTTON("Cancel", "Cancel the changes and dismiss the dialog"),
  OK_BUTTON("OK", "Save the changes and dismiss the dialog"),
  // ...
  ;

  private final String controlText;
  private final String toolTipText;

  ControlText(String controlText, String toolTipText) {
    this.controlText = controlText;
    this.toolTipText = toolTipText;
  }

  public String getControlText() { return controlText; }
  public String getToolTipText() { return toolTipText; }
}

Ignore the wisdom of using enumerations for this. There are other places that I want to do with similar things.

How to do this in Scala using scala.Enumeration? The Enumeration.Value class accepts only one row as a parameter. Do I need subclasses of it?

Thanks.

+3
source share
3 answers

You can do this, which matches how the enums are used:

sealed abstract class ControlTextBase
case class ControlText(controlText: String, toolTipText: String)
object OkButton extends ControlText("OK", "Save changes and dismiss")
object CancelButton extends ControlText("Cancel", "Bail!")
+13
source

:

object ControlText extends Enumeration {

  type ControlText = ControlTextValue

  case class ControlTextValue(controlText: String, toolTipText: String) extends Val(controlText)

  val CANCEL_BUTTON = ControlTextInternalValue("Cancel", "Cancel the changes and dismiss the dialog")
  val OK_BUTTON = ControlTextInternalValue("OK", "Save the changes and dismiss the dialog")

  protected final def ControlTextInternalValue(controlText: String, toolTipText: String): ControlTextValue = {
    ControlTextValue(controlText, toolTipText)
  }    
}

ControlText Java:

val c: ControlText
c.toolTipText

- withName apply. :

val c: ControlText = ControlText.withName(name).asInstanceOf[ControlText]
+6

After Mitch’s answer, if you find that the sealed behavior does not sufficiently limit the restriction of limiting the subclass of instances to a file where the base class is defined, you can use the definition of an object (module) as follows:

object ControlTexts {
  sealed abstract class ControlTextBase

  case class ControlText private[ControlTexts] (controlText: String, 
                                                toolTipText: String)
          extends ControlTextBase

  object OkButton     extends ControlText("OK", "Save changes and dismiss")
  object CancelButton extends ControlText("Cancel", "Bail!")
}

which, obviously, limits the further creation of ControlText instances. A sealed keyword is still important for identifying missing cases when matching with a sample.

+1
source

Source: https://habr.com/ru/post/1724498/


All Articles