0

Say i have enum like this:

  object Enm extends Enumeration {
        val ONE, TWO, THREE = Value
  }

and it's possible for me to get disired result by calling with name on it Enm.withName("ONE"), but if i have Value with argument, say:

object Enm extends Enumeration {
     val ONE = Value("1")
     val TWO = Value("2")
     val THREE = Value("3")
}

calling Enm.withName("ONE") i get back noting since it's now "1", "2" and so on. Is it possible somehow to get val names but not the ones i put in Value?

Dmitrii
  • 604
  • 2
  • 9
  • 30
  • why do you need that? i think perhaps the only way is to pattern match them. – Hongxu Chen Sep 28 '16 at 13:03
  • `Enm.values.filter(_.toString.startsWith("1")).max` for now i use this construction but i suspect that there should be more formal approach. – Dmitrii Sep 28 '16 at 13:09
  • why not use `Enm.withName("1")`? – Hongxu Chen Sep 28 '16 at 13:27
  • because of input i've got. So in my case i use Value's argument to print the full name of enum ordinal and i have to find it using input which in my case is the ONE, TWO, THREE – Dmitrii Sep 28 '16 at 14:47
  • but in fact you used "startsWith("1")", right? if you need to match "ONE", "TWO", "THREE" literal, perhaps you'd use pattern matching. – Hongxu Chen Sep 28 '16 at 14:51
  • i consider it as a temporary solution, if it's not possible i will back to something like `Value("ONE", "1")` and so on with some class that extends Val(string, string). – Dmitrii Sep 28 '16 at 15:44

1 Answers1

1

Hacky solution

Maintain a Map of word string to Number string mapping

object Enm extends Enumeration {
     val ONE = Value("1")
     val TWO = Value("2")
     val THREE = Value("3")
     val map = Map ("ONE" -> "1", "TWO" -> "2", "THREE" -> "3")
}

//Usage
Enm.withName(Enm.map("ONE"))

You cannot override withName method as it is final. So write a custom withName method

 object Enm extends Enumeration {
     val ONE = Value("1")
     val TWO = Value("2")
     val THREE = Value("3")
     private val map = Map ("ONE" -> "1", "TWO" -> "2", "THREE" -> "3")
     def customWithName(str: String) = withName(map(str))
 }

 //Usage
 Enm.customWithName("ONE")
Nagarjuna Pamu
  • 14,737
  • 3
  • 22
  • 40