0
votes

With Scala pattern matching, is it okay to write code that pattern matches on the type of the object? Isn't it as bad as using instanceOf operator of java, just that pattern matching makes the code look better. Is it ideal to pattern match on object type?

e.g.

abstract class Employee
class Manager extends Employee
class SE2 extends Employee
emp match {
   case m: Manager => ...
   case s: SE2 => ...
}

Now I understand it's okay to pattern match on types if the base is a sealed trait

2
Can you give a concrete example which you would want to match on object.type?Yuval Itzchakov
If the base type is a sealed trait then the compiler will warn you if the match cases are not exhaustive, i.e. don't cover all possible sub-types. If the base type is not sealed then you just need a good default case.jwvh
@jwvh but isn't comparing the type of object at runtime a code smell? pattern matching just beautifies it. in the end it's just something like instanceof underneathFaiz Halde

2 Answers

0
votes

but isn't comparing the type of object at runtime a code smell? pattern matching just beautifies it. in the end it's just something like instanceof underneath

Well, the alternative is usually adding an abstract method to the base type which isn't necessarily possible (if it isn't your own code) or better than pattern matching. You really need to judge it case-by-case instead of blindly saying to never or always use it.

0
votes

pattern matching just beautifies it

It does more than beautification :)

If you pattern match against irrelevant type compiler will give warning. Same if you miss a case when pattern matching a sealed trait.