sealed class A
class B1 extends A
class B2 extends A
Assuming we have a List of objects of class A
:
val l: List[A] = List(new B1, new B2, new B1, new B1)
And we want to filter out the elements of the type B1. Then we need a predicate and could use the following two alternatives:
l.filter(_.isInstanceOf[B1])
Or
l.filter(_ match {case b: B1 => true; case _ => false})
Personally, I like the first approach more, but I often read, one should use the match-case
statement more often (for reasons I do not know).
Therefore, the question is: Are there drawbacks of using isInstanceOf
instead of the match-case
statement ? When should one use which approach (and which approach should be used here and why) ?
There are no difference
cat t.scala:
$ scalac -print t.scala
The advantage of
match-case
is that you don't have to cast the object in case you want to perform operations on it that depend on its narrower type.In the following snippet, using
isInstanceOf
seems to be fine since you don't perform such an operation:However, if you do the following:
then I'd be in favour of using
match-case
:It is slightly annoying that you have to include the "otherwise"-case, but using
collect
(as hinted at by om-nom-nom) could help, at least if you work with collections inherit from Seq:You can filter like that:
That is much more readable, IMO.
There's no problem using
isInstanceOf
, as long as you don't useasInstanceOf
.Code that uses both is brittle, because checking and casting are separate actions, whereas using matching you have a single action doing both.