使用java多年后我试图进入scala。 假设我有一个像这样的简单枚举
public enum Foo{
Example("test", false),
Another("other", true);
private String s;
private boolean b;
private Foo(String s, boolean b){
this.s = s;
this.b = b;
}
public String getSomething(){
return this.s;
}
public boolean isSomething(){
return this.b;
}
}
有关于stackoverflow的文档和一些帮助,我得到了:
object Foo extends Enumeration
{
type Foo = Value
val Example, Another = Value
def isSomething( f : Foo) : Boolean = f match {
case Example => false
case Another => true
}
def getSomething( f : Foo) : String = f match {
case Example => "test"
case Another => "other"
}
}
但我不喜欢这个有几个原因。 首先,值分散在整个方法中,每次添加新条目时我都需要更改它们。 其次,如果我想调用一个函数,它将采用Foo.getSomething(Another)或类似的形式,我觉得很奇怪,我更喜欢Another.getSomething。 我会很感激有一些提示,可以将它改成更优雅的东西。
答案 0 :(得分:7)
是否有必要使用Enumeration
?
您可以使用sealed abstract class
和case object
:
sealed abstract class Foo(val something: String, val isSomething: Boolean)
case object Example extends Foo ("test", false)
case object Another extends Foo ("other", true)
如果你忘记了Foo
个实例,你会收到警告:
scala> def test1(f: Foo) = f match {
| case Example => f.isSomething
| }
<console>:1: warning: match may not be exhaustive.
It would fail on the following input: Another
def test1(f: Foo) = f match {
您还可以向枚举实例添加方法:
implicit class FooHelper(f: Foo.Value) {
def isSomething(): Boolean = Foo.isSomething(f)
}
scala> Foo.Example.isSomething
res0: Boolean = false