tags:

views:

150

answers:

2

I am writing my first large Scala program. In the Java equivalent, I have an enum that contains labels and tooltips for my UI 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; }
}

Never mind the wisdom of using enums for this. There are other places that I want to do similar things.

How can I do this in Scala using scala.Enumeration? The Enumeration.Value class takes only one String as a parameter. Do I need to subclass it?

Thanks.

+4  A: 

You could do this which matches how 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!")
Mitch Blevins
I use this idiom too for all the enumerated types.
paradigmatic
Better than my answer,k that's for sure
oxbow_lakes
It is better to have an `sealed abstract class` as parent, then the case classes or objects desired, and then, if you want specific instances of a case class, _normal_ objects instead of case objects.
Daniel
Edited to reflect my understanding of Daniel Sobral's comment. Daniel, what is the benefit of having the ControlTextBase abstract class here? Is it just for flexibility?
Mitch Blevins
A: 

Following on from Mitch's answer, if you find that the sealed behaviour is not restrictive enough in limiting subclassed instances to the file where the base class is defined, you can use an object (module) definition like this:

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 further instantiation of ControlText instances. The sealed keyword is still important in helping detect missing cases in pattern matching.

Don Mackenzie