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.
You’re getting a
MatchErrorin the case where yourcommonis not aLeafNode. Yourifandmatchexpressions are not equivalent. I think the most direct way to make them equivalent is: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
returnin the middle. Remember that match is an expression, so that something like this may be possible: