Question

It would be great, if it is possible to extend the Scala enumeration value type in a way, that a kind of tree structure accrues. I mean something like that:

[Examples are just pseudo code!]

object SomeSubEnum extends Enumeration {
  type SomeSubEnum = Value

  val SubA, SubB, SubC = Value
}

object SomeTopEnum extends Enumeration {
  type SomeTopEnum = Value

  val TopA = Value("TopA", Subs = List(SomeSubEnum.SubA, SomeSubEnum.SubB))
  val TopB = Value("TopB", Subs = List(SomeSubEnum.SubC))
  val TopC = Value("TopC", Subs = List(SomeSubEnum.SubA, SomeSubEnum.SubB, SomeSubEnum.SubC))
}


Usage:

def doSomething(param: SomeTopEnum) = {
  someTopEnum.Subs.forAll(sub => doMore(sub))
}


doSomethingElse(SomeTopEnum.TopA.Subs.SubB) // Subs could be a map


I am new at Scala, in other languages I would create a kind of static class tree structure to do that, but maybe there is a better solution in Scala.

[sorry for my poor English]

Was it helpful?

Solution

Could you use case classes for this instead? The enumeration type in Scala isn't generally that useful IMO. Something along the lines of (off the top of my head):

sealed abstract class MyEnum[A]
case class SubEnum[A](value : A) extends MyEnum[A]
case class TopEnum[A](value : A, subs : List[SubEnum[A]]) extends MyEnum[A]

This would allow you to do things like:

val top = TopEnum("top value", List(SubEnum("sub value 1"), SubEnum("sub value 2")))

and then:

top.subs map (println(_))

or:

for(s <- top.subs) println(s.value)

Or any pattern matching you might want to do as well. If you wanted to restrict the types of the type parameter (A) then you could define a top level case class which all sub classes must be a subtype of:

sealed abstract class EnumValue(a : String)
case class EnumValue1 extends EnumValue("value 1")
case class EnumValue2 extends EnumValue("value 2")

...etc....

sealed abstract class MyEnum[A <: EnumValue]
case class SubEnum[A <: EnumValue](value : A) extends MyEnum[A]
case class TopEnum[A <: EnumValue](value : A, List[SubEnum[A]]) extends MyEnum[A]

Bit verbose, but will probably do what you want...

Hope this helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top