Dmitrii
Dmitrii

Reputation: 624

Accessing enum Values in enum in scala

Is there any possible solution in scala. I've got Enum with Value, whose elements are of another enum.

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
}

In java it's possible to getEnumConstants() and fill up Map of type . Is there any chance to do this in scala?

Upvotes: 0

Views: 604

Answers (1)

Tzach Zohar
Tzach Zohar

Reputation: 37832

Following your attempt - looks like you have no choice but to cast nt into a CustomVal (you know that this enum's values are of that type, because that's how you built them), so a working (yet ugly) version of your code would be something like:

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)
}

Which would produce:

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))

However, when faced with such solutions I just revert to the good-old Java enums, as they can easily be used by Scala code and are less... clunky.

Upvotes: 2

Related Questions