Search code examples
scalaadt

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
    .filter(_.isInstanceOf[Foo])
    .map(_.asInstanceOf[Foo])

  val bars = modifiers
    .filter(_.isInstanceOf[Bar])
    .map(_.asInstanceOf[Bar])

}

Is there a better way to extract all the Foos and all the Bars from the modifiers?


Solution

  • def apiMethod(modifiers: Foolike*) = {
    
        @tailrec
        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...