Scala中的枚举具有多个构造函数参数

Ral*_*lph 5 enums scala

我正在编写我的第一个大型Scala程序.在Java等价物中,我有一个枚举,其中包含我的UI控件的标签和工具提示:

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; }
}
Run Code Online (Sandbox Code Playgroud)

别介意使用枚举的智慧.还有其他地方我想做类似的事情.

如何使用scala.Enumeration在Scala中执行此操作?Enumeration.Value类只接受一个String作为参数.我需要继承它吗?

谢谢.

Mit*_*ins 16

你可以这样做,以匹配枚举的使用方式:

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!")
Run Code Online (Sandbox Code Playgroud)

  • 我从Scala开始,但在这种状态下,我会说它缺少一些东西:"ControlText"应该扩展"ControlTextBase",是或否? (5认同)
  • 编辑反映了我对Daniel Sobral评论的理解.Daniel,在这里拥有ControlTextBase抽象类有什么好处?它只是为了灵活性吗? (2认同)

小智 8

我想就此问题提出以下解决方法:

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)
  }    
}
Run Code Online (Sandbox Code Playgroud)

现在您可以使用ControlTextJava枚举:

val c: ControlText
c.toolTipText
Run Code Online (Sandbox Code Playgroud)

唯一有点难闻的气味是通过withNameapply方法获得枚举对象.你必须做一个演员:

val c: ControlText = ControlText.withName(name).asInstanceOf[ControlText]
Run Code Online (Sandbox Code Playgroud)