0

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]

Basti
  • 130
  • 1
  • 9

1 Answers1

1

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

Jonny Coombes
  • 575
  • 2
  • 6
  • Actually, to give you a more flexible structure, you can simply just change the definition of TopEnum to: case class TopEnum[A <: EnumValue](value : A, List[MyEnum[A]]) extends MyEnum[A]. That way, you could have a list of mixed TopEnums and SubEnums... – Jonny Coombes Dec 09 '13 at 13:47
  • For additional Java enum like features in a nice package. See this guys post http://stackoverflow.com/a/27441788/1148030 – Peter Lamberg Feb 17 '15 at 19:44