我正在编写我的第一个大型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)
小智 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)
唯一有点难闻的气味是通过withName或apply方法获得枚举对象.你必须做一个演员:
val c: ControlText = ControlText.withName(name).asInstanceOf[ControlText]
Run Code Online (Sandbox Code Playgroud)