1

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?

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
user504909
  • 9,119
  • 12
  • 60
  • 109
  • 3
    No packages, it comes for free. `.withName` is the method you are looking for. `val s:CVVStatus = CVVStatus.withName(tmp)` – Alec Aug 18 '16 at 00:20

2 Answers2

0

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.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
0

You may also consider using case objects. For reference, check these stackoverflow answers Case Objects vs Enumerations How to access objects within an object by mixing in a trait with reflection?

Community
  • 1
  • 1
zudokod
  • 4,074
  • 2
  • 21
  • 24