Search code examples
scalaenumeration

Scala: How to get Enumeration element based on values and labels?


I have two enum classes defined as the following.

object Rating extends Enumeration {
  type Rating = Value
  val LOW: Value = Value("Low")
  val AVERAGE: Value = Value("Average")
  val HIGH: Value = Value("High")
}

object Reason extends Enumeration {
  type Reason = Value
  val MISSING_PARTS: Value = Value(1)
  val WRONG_ITEM: Value = Value(2)
  val DEFECTIVE_ITEM: Value = Value(3)
}
  1. How can I get the Rating based on the String values "Low", "Average" and "High"

  2. How can I get the Reason based on the Integer values 1, 2, 3

  3. How can I get the Reason based on the val name MISSING_PARTS, WRONG_ITEM, DEFECTIVE_ITEM

Please correct me if I am not using the correct terminology. I am from Java background and new to Scala. I did a lot of searches but either they are outdated or they use very trivial examples where the labels and values are the same strings, which does not help much.

Any help will be appreciated.


Solution

    1. Rating.withName("Low")
    2. Reason(1) (which is shorthand for Reason.apply(1))
    3. Reason.withName("DEFECTIVE_ITEM")

    Explanation:

    Each enumeration value has an id and a name. Both are generated using a default unless you override them using the appropriate Value(...) overload. In this case, Rating has customized names and Reason has customized IDs. Given the code above, these are the names and ids assigned to each value:

    val LOW: Value = Value("Low")         // Id: 0; Name: Low
    val AVERAGE: Value = Value("Average") // Id: 1; Name: Average
    val HIGH: Value = Value("High")       // Id: 2; Name: High
    
    val MISSING_PARTS: Value = Value(1)   // Id: 1; Name: MISSING_PARTS
    val WRONG_ITEM: Value = Value(2)      // Id: 2; Name: WRONG_ITEM
    val DEFECTIVE_ITEM: Value = Value(3)  // Id: 3; Name: DEFECTIVE_ITEM
    

    Now, we can access specific values using either withName(name: String) or apply(id: Int) which references values based on names and ids respectively.