0

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?

1

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, thx this works, but to make it work i had to explicitly cast ValueSet .toSeq, so it turns out that enumeration support in java more reach, imho.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.