2009-12-02 103 views
3

我正在编写我的第一个大型Scala程序。在Java等价,我有一个包含标签和工具提示我的UI控件枚举:在Scala中枚举多个构造函数参数

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; } 
}

没关系使用枚举该的智慧。还有其他地方,我想做类似的事情。

我该如何在Scala中使用scala.Enumeration来做到这一点? Enumeration.Value类只接受一个字符串作为参数。我需要继承吗?

谢谢。

回答

13

你能做到这一点它匹配如何枚举使用:

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!") 
+0

我也使用这个习语所有枚举类型。 – paradigmatic 2009-12-02 16:01:43

+0

比我的回答更好,k肯定是 – 2009-12-02 17:35:53

+1

最好有一个“密封的抽象类”作为父类,然后是所需的类或对象,然后,如果你想要一个case类的特定实例,可以使用_normal_对象而不是案件对象。 – 2009-12-02 17:41:21

1

从米奇的回答继,如果发现密封的行为是不够的限制性的限制子类的实例的文件,其中的基类定义如下:

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!") 
} 

这明显限制了ControlText实例的进一步实例化。密封关键字对于帮助检测模式匹配中的缺失情况仍然很重要。

6

我想提出这个问题了以下解决方法:

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 

唯一一点不好的气味是让枚举通过withNameapply方法对象。你必须做一个演员:

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