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
object.type
? – Yuval Itzchakovmatch
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 defaultcase
. – jwvh