Enums with parameters and methods in scala
enums, scala
Solution
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
Problem
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.