Scala match error

前端 未结 2 1400
执笔经年
执笔经年 2020-12-31 02:47

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

相关标签:
2条回答
  • 2020-12-31 03:37

    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 讨论(0)
  • 2020-12-31 03:53

    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
      }
    }
    
    0 讨论(0)
提交回复
热议问题