2

在使用 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。我将不胜感激有关将其更改为更优雅的一些提示。

4

1 回答 1

9

有必要使用Enumeration吗?

你可以使用sealed abstract classand 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
于 2013-04-01T11:25:32.253 回答