user504909 user504909 - 3 months ago 22
Scala Question

How to reflect Enumeration class in scala?

I have a Scala Enumeration and I want to get the Enumeration value from

String
.

object CVVStatus extends Enumeration {
type CVVStatus = Value
val PRESENT, NOT_PRESENT, VALID, INVALID = Value
}


I want to do something like this:

val prop = new Properties()
prop.load(new FileInputStream("config.conf"))
val tmp = prop.getProperty(propname)
val s:CVVStatus = StringtoEmum(tmp)


If I need lots of enumeration from different Enumeration object-name to enumeration objects, how should I accomplish this? What package should I import?

Answer

As @Alec points out in a comment, this is 'for free' with the Enumeration class, and it is easy to see in a worksheet:

object CVVStatus extends Enumeration {
  type CVVStatus = Value
  val PRESENT, NOT_PRESENT, VALID, INVALID = Value
}

val test_present = "PRESENT"  // test_present: String = PRESENT
val test_incorrect = "INCORRECT"  // test_incorrect: String = INCORRECT
val enumeration_present = CVVStatus.withName(test_present)  // enumeration_present: CVVStatus.Value = PRESENT
val enumeration_incorrect = CVVStatus.withName(test_incorrect)  //java.util.NoSuchElementException: No value found for 'INCORRECT'

This last one fails, because it is not a valid enumeration. The withName documentation reads:

Return a Value from this Enumeration whose name matches the argument s. The names are determined automatically via reflection.

No imports necessary.