Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala match error

Tags:

scala

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.

like image 560
Andriy Drozdyuk Avatar asked Feb 15 '11 05:02

Andriy Drozdyuk


People also ask

What is match error in Scala?

This class implements errors which are thrown whenever an object doesn't match any pattern of a pattern matching expression.

What is matchers in Scala?

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.


1 Answers

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
  }
}
like image 123
Lachlan Avatar answered Oct 17 '22 07:10

Lachlan