简体   繁体   English

Scala:使用带有valueOf的Java枚举和参数化函数

[英]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. 我正在处理一些Java / Scala混合代码,并且由于我对Scala不太Scala ,所以遇到了一个似乎应该很容易解决的问题,但这使我感到困惑。

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: 我在Java中有许多枚举,我想做的是编写一个通用的参数化Scala函数,该函数采用List[String]并将其转换为Set的枚举值:

// 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. 这是行不通的,因为我们不能将T用作T.valueOf ,据我所知。 I suspect that we have to instead use the Enum.valueOf(Class<T> enumType, String s) method. 我怀疑我们必须改为使用Enum.valueOf(Class<T> enumType, String s)方法。 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 ? 如果是这样,我该如何传递cls Say I have a specific instance I want to call with an enum called MyEnum and a List[String] called values : 说我有一个具体的例子我想与一个叫enum称为MyEnumList[String]所谓的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. 当然,避免必须传递cls是理想的选择,但我不确定是否有可能。 Thanks for any help you can give me! 感谢你给与我的帮助!

This works for me: 这对我有用:

X.java: X.java:

public enum X {
    a,
    b,
    c
}

Test.scala: 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"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM