Filtering a Scala List by type

后端 未结 3 1556
暗喜
暗喜 2020-12-25 11:09

I have a class structure like this

abstract class A
class B extends A
class C extends A
class D extends A
class E extends A

and I have a co

相关标签:
3条回答
  • 2020-12-25 11:43

    flatMap that shit! (as they say):

    scala> val ys = xs flatMap {
         |   case _: B | _: C => None
         |   case other => Some(other)
         | }
    ys: List[A] = List(D@7ecdc97b, E@2ce07e6b, E@468bb9d1)
    

    In your case you were getting a List[ScalaObject] because ScalaObject is the least upper bound of None, D, and E.

    0 讨论(0)
  • 2020-12-25 11:47

    Formulating problems as questions seems to be a pretty good way of solving them :) My question actually provides the answer - just filter by subtype:

    val ys = xs filterNot(List(classOf[B], classOf[C]) contains _.getClass)
    
    0 讨论(0)
  • 2020-12-25 11:51

    collect can be used to filter values on which the function is defined:

    Get all values of type A:

    xs.collect { case a: A => a }
    

    Get all values except B and C:

    xs diff xs.collect { case x@(_: B | _: C) => x }
    
    0 讨论(0)
提交回复
热议问题