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 a Vector right away, if not - I continue with the method.
So originally I had:
//code here
if (common.isInstanceOf[LeafNode]) {
return Vector(common.asInstanceOf[LeafNode].data)
}
//code here
then I tried to replace it with:
//code here
common match {
case leaf: LeafNode => return Vector(leaf.data)
}
//code here
but I get scala.MatchError.
This class implements errors which are thrown whenever an object doesn't match any pattern of a pattern matching expression.
It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C. Here, “match” keyword is used instead of switch statement. “match” is always defined in Scala's root class to make its availability to the all objects.
You're getting a MatchError
in the case where your common
is not a LeafNode
. Your if
and match
expressions are not equivalent. I think the most direct way to make them equivalent is:
common match {
case leaf: LeafNode => return Vector(leaf.data)
case _ =>
}
But I'd recommend looking at the whole code block and working out are more functional way to do this job. That is, without the return
in the middle. Remember that match is an expression, so that something like this may be possible:
def foo = {
//code here
common match {
case leaf: LeafNode => Vector(leaf.data)
case notLeaf: Branch => //code here
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With