Christopher Ambler
Christopher Ambler

Reputation: 700

How to convert from Scala string to Java enum

I have an API that receives a string representing a language. My Scala code (using Scalatra for the API) calls into existing Java code that I must support. This Java code expects the language to be in the form of an enum that it defines.

I could exhaustively pattern match on the string to return the proper enum element, but I have to believe there's a better way?

For example, I could do this:

      f.language.value.get.toUpperCase.split(",").map {
        case "ALL" => JavaLanguageEnum.ALL
        case "AAA" => JavaLanguageEnum.AAA
        case "BBB" => JavaLanguageEnum.BBB
        case "CCC" => JavaLanguageEnum.CCC
        case "DDD" => JavaLanguageEnum.DDD
        case "EEE" => JavaLanguageEnum.EEE
        case "FFF" => JavaLanguageEnum.FFF
        case _ => JavaLanguageEnum.ALL
      }.toList

... but that would be a pretty big piece of code to do this work. Is there a better way to simply say, "if the string matches one of the enums, return that enum so I can pass it in?"

Upvotes: 0

Views: 756

Answers (1)

resueman
resueman

Reputation: 10613

Java's Enum actually already has a method to handle this; valueOf. Just pass the String to the method, and wrap it in a try...catch block to handle the case where it doesn't match.

f.language.value.get.toUpperCase.split(",").map {
  try {
    JavaLanguageEnum.valueOf(_)
  } catch {
    case e: IllegalArgumentException => JavaLanguageEnum.ALL
  }
}

Upvotes: 6

Related Questions