开发者

Scala match error

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 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
  }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜