Enums with parameters and methods in scala -


after using java many years trying scala. lets have simple enum 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 docu , on stackoverflow got far as:

object foo extends enumeration {   type foo = value   val example, = value    def issomething( f : foo) : boolean = f match {     case example => false     case => true   }      def getsomething( f : foo) : string = f match {     case example => "test"     case => "other"   } } 

but don't several reasons. first values scattered on methods , need change them everytime add new entry. second if want call function in form of foo.getsomething(another) or that, find strange rather another.getsomething. appreciate tips on changing more elegant.

is necessary use enumeration?

you use sealed abstract class , case object:

sealed abstract class foo(val something: string, val issomething: boolean)  case object example extends foo ("test", false) case object extends foo ("other", true) 

you'll warning if you'll forget of foo instances:

scala> def test1(f: foo) = f match {      |   case example => f.issomething      | } <console>:1: warning: match may not exhaustive. fail on following input:        def test1(f: foo) = f match { 

you add methods enumeration instances:

implicit class foohelper(f: foo.value) {   def issomething(): boolean = foo.issomething(f) }  scala> foo.example.issomething res0: boolean = false 

Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -