scala中是否有任何可能的解决方案。我已经获得了Enum with Value,其元素属于另一个枚举。
object NumEnum extends Enumeration {
val EVEN = Value(TWO, FOUR, SIX)
val ODD = Value(ONE, THREE, FIVE)
val numbersByType = for {
nt <- NumberEnum.values
n <- nt.[here i wanna collection values but the only thing i can get is.id of enum]
} yield
...
class CustomVal(val nums: Num) extends Val
protected final def Value(nums: Num): CustomVal = new CustomVal(nums)
}
class Num extends Enumeration {
val ONE, TWO, THREE, FOUR, FIVE, SIX = Value
}
在java中,可以使用getEnumConstants()并填充类型的Map。 scala中有没有机会这样做?
答案 0 :(得分:1)
在您尝试之后 - 看起来您别无选择,只能将 nt
投射到CustomVal
(您知道此枚举的值属于该类型,因为这是如何你构建它们,所以你的代码的工作(但丑陋)版本将是:
object Num extends Enumeration {
val ONE, TWO, THREE, FOUR, FIVE, SIX = Value
}
object NumEnum extends Enumeration {
import Num._
val EVEN = Value(TWO, FOUR, SIX)
val ODD = Value(ONE, THREE, FIVE)
val numbersByType = for {
nt <- NumEnum.values
n <- nt.asInstanceOf[CustomVal].nums // ugly casting
} yield (nt, n) // I'm assuming you want something like this?
class CustomVal(val nums: Seq[Num.Value]) extends Val
protected final def Value(nums: Num.Value*): CustomVal = new CustomVal(nums)
}
哪会产生:
scala> NumEnum.numbersByType
res0: scala.collection.immutable.SortedSet[(NumEnum.Value, Num.Value)] = TreeSet((EVEN,TWO), (EVEN,FOUR), (EVEN,SIX), (ODD,ONE), (ODD,THREE), (ODD,FIVE))
然而,当面对这样的解决方案时,我只是回到了古老的Java枚举,因为它们可以很容易地被Scala代码使用,并且不那么......笨重。