Swalker Swalker - 1 year ago 77
Scala Question

How to seperate Seq of super type into Seqs of subtype

Let's say I have this kind of hierarchy for my Data:

sealed trait Foolike
case class Foo extends Foolike
case class Bar extends Foolike
case class Baz extends Foolike

Now I want to create an API where you can put in any of these arguments like this:

def apiMethod(modifiers: Foolike*) = {

val foos = modifiers

val bars = modifiers


Is there a better way to extract all the
s and all the
s from the

Answer Source
def apiMethod(modifiers: Foolike*) = {

    def foosAndBarsAndBazs(mods: List[Foolike], foos: List[Foo], bars: List[Bar], bazs: List[Baz]): (List[Foo], List[Bar], List[Baz]) = mods match {
        case Nil => (foos, bars, bazs)
        case (foo: Foo) :: tail => foosAndBarsAndBazs(tail, foo :: foos, bars, bazs)
        case (bar: Bar) :: tail => foosAndBarsAndBazs(tail, foos, bar :: bars, bazs)
        case (baz: Baz) :: tail => foosAndBarsAndBazs(tail, foos, bars, baz :: bazs)

    val (foos, bars, bazs) = foosAndBarsAndBazs(modifiers.toList, Nil, Nil, Nil)        

This is a tail recursive solution. Of course, you could have just map over modifiers and pattern match to get a tuple of Options and then flatten them, but then you'd traverse each list one more time...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download