0

In Scala, I create a list and then filter it based on a class condition:

val list: List[MyObj] = // fill in with objects that extend MyObj, one of them is class A
val list2 = list filter ({ case A() => false case _ => true })

Is it possible to write the above filter in a more concise form?

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
Brandon McHomery
  • 173
  • 1
  • 10
  • possible duplicate of [When to use isInstanceOf and when to use a match-case-statement (in Scala)?](http://stackoverflow.com/questions/11229265/when-to-use-isinstanceof-and-when-to-use-a-match-case-statement-in-scala) – Sascha Kolberg Jul 27 '15 at 18:23

1 Answers1

2

You could try using the isInstanceOf method:

list filter (_.isInstanceOf[A])
bedwyr
  • 5,774
  • 4
  • 31
  • 49
  • I wasn't aware of the recommendation against that method. What course are you referring to? – bedwyr Jul 27 '15 at 17:36
  • 1
    Imho, the main advantage of using type match would be the return type of the filter. If list is a `List[B]`, `list filter (_.isInstanceOf[A])` returns a `List[B]`. If you do `list.collect { case a: A => a }` you get a `List[A]`. Might be handy in some cases. – Sascha Kolberg Jul 27 '15 at 18:21