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 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
于 2013-04-01T11:25:32.253 に答える