I tried to replace my isInstanceOf check with a match, but it does not work.
In my method I do a check for a tree node - if it is a leaf - I want to return it inside
The problem is that the set of cases in your match
block is not exhaustive; if common
is anything but a LeafNode
, a MatchError
will be thrown. You can solve this by having a catch-all case like so:
common match {
case leaf: LeafNode => return Vector(leaf.data)
... // other cases
case other => ... // what to do if nothing else matches
}
This is analogous to the default
case in a Java switch statement. The other
case is called an "irrefutable pattern" because it has no characteristics; it doesn't require a particular type or constructor, so it will always match anything that falls through to it. The name of the variable doesn't have to be other
, it can be anything you want, or even _
... in fact you don't need to bind a new variable here since it will be identical to common
.
On a point of style, it's generally bad form to put return statements inside of a match
block; the entire block is an expression which evaluates to one of its cases, so just return the entire expression. Also, you don't need to use the return
keyword at all, as the last expression in a function definition will be used as the result.