Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala/Java enumerations

I've read this and this, but I still don't understand the (idiomatic) equivalent way to do this in Scala

enum Status { 
    OK(1, "Ok", "Okay"),
    NOT_OK(5, "Not Ok", "Not Okay")
    BAD(10, "Bad", "Run for your life")

    int code;
    String name;
    String description; // custom fields

    Status(int code, String name, String description) {
        this.code = code;
        this.name = name;
        this.description = description;
    }
}

class Main {
    public static void main(String[] args) {
        for(Status status : Status.values) { // iterate through them
            doStuff(status);
        }
    }

    private doStuff(Status status) {
        System.out.println(status.description);
        // and more
    }
}
like image 223
Paul Draper Avatar asked Dec 09 '22 09:12

Paul Draper


1 Answers

In Scala you can create a Enumeration structure which is close to "enum" from Java. Basically, what you need to do is just to extend a scala.Enumeration class and to extend a Val class if you need a more complicated class as a enum. Otherwise, you can use default Val class which takes Int or String or Both. Below, is a Scala version of your Java code.

object Status extends Enumeration {

  case class StatusVal(code: Int, name: String, description: String) extends Val

  val OK = StatusVal(1, "Ok", "Okay")
  val NOT_OK = StatusVal(1, "Not Ok", "Not Okay")
  val BAD = StatusVal(1, "Bad", "Run for your life")
}

object Application extends App {
  Status.values foreach (s => println(s.asInstanceOf[StatusVal].description))
}
like image 123
kikulikov Avatar answered Dec 21 '22 11:12

kikulikov