2

after using java for many years I am trying to get into scala. Lets say I have a simple enum like this

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;
  }
}

with the docu and some help on stackoverflow I got as far as:

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"
  }
}

But I don't like this for several reasons. First the values are scattered all over the methods and I would need to change them everytime I add a new entry. Second if I want to call a function it would be in the form of Foo.getSomething(Another) or something like that, which I find very strange I rather would like Another.getSomething. I would appreciate some tips on changing this to something more elegant.

1 Answers1

9

Is it necessary to use Enumeration?

You could use sealed abstract class and 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)

You'll get a warning if you'll forget some of Foo instances:

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 {

You could also add methods to your enumeration instances:

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

scala> Foo.Example.isSomething
res0: Boolean = false
senia
  • 37,745
  • 4
  • 88
  • 129
  • No, it is not necessary to use Enumeration. I will look into these sealed case classes more thanks for the answer =) –  Apr 01 '13 at 11:40
  • @sourcedelica, `FooHelper` is for `object Foo extends Enumeration`, not for `sealed abstract class Foo`. There is direct call `f.isSomething` in my answer. – senia Apr 01 '13 at 22:41
  • ahh - sorry, i missed that. – sourcedelica Apr 01 '13 at 23:22