Sebastian
Sebastian

Reputation: 795

Scala: using Java enums and parameterized functions with valueOf

I'm working on some mixed Java / Scala code, and since I'm somewhat new to Scala, I'm running into an issue that seems that it should be easy to solve, but that has me stumped.

I have a number of enums in Java, and what I'd like to do is write a generic parameterized Scala function that takes a List[String] and converts it to a Set of enum values:

// Not sure if <: is the right operator to say T is a Java enum here.
def strToEnumSet[T <: Enum[T]](values: List[String]): Set[T] =
values.map(x => T.valueOf(x)).toSet

This doesn't work, since we can't use T as T.valueOf, which I understand. I suspect that we have to instead use the Enum.valueOf(Class<T> enumType, String s) method. However, I'm not sure the syntax to do this properly.

Do I need to do something like:

def strToEnumSet[T <: Enum[T]](cls: Class[T], values: List[String]): Set[T] =
   values.map(x => Enum.valueOf(cls, x)).toSet

And if so, what do I pass in for cls? Say I have a specific instance I want to call with an enum called MyEnum and a List[String] called values:

val myEnumSet: Set[MyEnum] = strToEnumSet[MyEnum](???, values)

What would I pass in for ???

Of course, avoiding having to pass in cls would be ideal, but I'm not sure that's possible. Thanks for any help you can give me!

Upvotes: 0

Views: 234

Answers (1)

Rado Buransky
Rado Buransky

Reputation: 3294

This works for me:

X.java:

public enum X {
    a,
    b,
    c
}

Test.scala:

val a = strToEnumSet(classOf[X], List("a"))

Possible improvement:

def strToEnumSet[T <: Enum[T]](values: Iterable[String])(implicit m: Manifest[T]): Set[T] =
values.map(x => Enum.valueOf(m.runtimeClass.asInstanceOf[Class[T]], x)).toSet

You can call it like this:

val a = strToEnumSet[X](List("a"))

Upvotes: 1

Related Questions