Randomize
Randomize

Reputation: 9103

Scala: How to avoid check instance and casting

I found myself sometimes in the condition of running:

someCollection.filter(_.isInstanceOf[Foo]).asInstanceOf[List[Foo]]

just to check if the collection has the instances of Foo and casting the final filtered collection.

Is there a better way to do that (assuming I cannot change the current data structure)?

I tried with:

someCollection.map(case c: Foo => c)

but at runtime it returns MatchingError as of course it is looking for all the remaining cases (case _ =>).

Upvotes: 0

Views: 62

Answers (1)

Pascal Soucy
Pascal Soucy

Reputation: 1317

someCollection.collect { case c: Foo => c }

Upvotes: 4

Related Questions