Scala匹配错误

And*_*yuk 17 scala

我试图用匹配替换我的isInstanceOf检查,但它不起作用.

在我的方法中,我检查树节点 - 如果它是叶子 - 我想立即将它返回到Vector中,如果不是 - 我继续使用该方法.

所以最初我有:

    //code here
    if (common.isInstanceOf[LeafNode]) {
        return Vector(common.asInstanceOf[LeafNode].data)
    }
    //code here
Run Code Online (Sandbox Code Playgroud)

然后我试着用以下代替:

    //code here
     common match {
        case leaf: LeafNode => return Vector(leaf.data)
    }
    //code here
Run Code Online (Sandbox Code Playgroud)

但我得到了scala.MatchError.

Lac*_*lan 26

在你不是MatchError的情况下,你得到了common一个LeafNode.你ifmatch表达方式并不相同.我认为使它们等效的最直接方法是:

common match {
  case leaf: LeafNode => return Vector(leaf.data)
  case _ =>
}
Run Code Online (Sandbox Code Playgroud)

但是我建议查看整个代码块,并找出更实用的方法来完成这项工作.也就是说,没有return在中间.请记住,匹配是一个表达式,所以这样的事情可能是这样的:

def foo = {
  //code here
  common match {
    case leaf: LeafNode => Vector(leaf.data)
    case notLeaf: Branch => //code here
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 你为什么用return? (2认同)

Tom*_*ett 5

问题是你的match区块中的一组案例并非详尽无遗; 如果common不是a LeafNode,MatchError则会被抛出.你可以通过这样一个包罗万象的案例来解决这个问题:

common match {
  case leaf: LeafNode => return Vector(leaf.data)
  ... // other cases
  case other => ... // what to do if nothing else matches
}
Run Code Online (Sandbox Code Playgroud)

这类似于defaultJava switch语句中的情况.这种other情况被称为"无可辩驳的模式",因为它没有特征; 它不需要特定的类型或构造函数,因此它将始终匹配任何落在它上面的东西.变量的名称不一定是other,它可以是你想要的任何东西,甚至_......实际上你不需要在这里绑定一个新的变量,因为它将是相同的common.

在一个风格点上,将return语句放在一个match块中通常是不好的形式; 整个块是一个表达式,它根据其中一个案例进行求值,因此只返回整个表达式.此外,您根本不需要使用return关键字,因为函数定义中的最后一个表达式将用作结果.