scalacastingscala-collectionsdescendant

Extract sublist of descendants in Scala


I have a class Foo extends Bar and a List or other collection of base class:

val bars: Iterable[Bar] 

I need to extract all Foo elements from the collection. The following is the code:

val fooes: Iterable[Foo] = bars
    .filter(x => Try(x.isInstanceOf[Foo]).isSuccess))
    .map(_.isInstanceOf[Foo])

Is there conciser approach?


Solution

  • val fooes: Iterable[Foo] = bars.collect{case foo:Foo => foo}
    

    The .collect() method takes a partial-function as its parameter. In this case the function is defined only for Foo types. All others are ignored.