在scala中包含参数和方法的枚举

Noz*_*rum 2 enums scala

使用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;
  }
}
Run Code Online (Sandbox Code Playgroud)

随着文档和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"
  }
}
Run Code Online (Sandbox Code Playgroud)

但出于几个原因,我不喜欢这个.首先,值分散在整个方法中,每次添加新条目时我都需要更改它们.其次,如果我想调用一个函数,它将采用Foo.getSomething(Another)或类似的形式,我觉得很奇怪,我更喜欢Another.getSomething.我会很感激一些提示,将它改成更优雅的东西.

sen*_*nia 8

有必要使用Enumeration吗?

你可以使用sealed abstract classcase 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)
Run Code Online (Sandbox Code Playgroud)

如果你忘记了一些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 {
Run Code Online (Sandbox Code Playgroud)

您还可以向枚举实例添加方法:

implicit class FooHelper(f: Foo.Value) {
  def isSomething(): Boolean = Foo.isSomething(f)
}

scala> Foo.Example.isSomething
res0: Boolean = false
Run Code Online (Sandbox Code Playgroud)