我尝试用匹配项替换 isInstanceOf 检查,但它不起作用。
在我的方法中,我检查树节点 - 如果它是叶子 - 我想立即将其返回到 Vector 中,如果不是 - 我继续该方法。
所以最初我有:
//code here
if (common.isInstanceOf[LeafNode]) {
return Vector(common.asInstanceOf[LeafNode].data)
}
//code here
然后我尝试将其替换为:
//code here
common match {
case leaf: LeafNode => return Vector(leaf.data)
}
//code here
但我得到了 scala.MatchError。
最佳答案
如果您的 common
不是 LeafNode
,您将收到 MatchError
。您的 if
和 match
表达式并不等效。我认为使它们等效的最直接方法是:
common match {
case leaf: LeafNode => return Vector(leaf.data)
case _ =>
}
但我建议查看整个代码块并找出更实用的方法来完成这项工作。也就是说,中间没有 return
。请记住,匹配是一个表达式,因此这样的事情可能是可能的:
def foo = {
//code here
common match {
case leaf: LeafNode => Vector(leaf.data)
case notLeaf: Branch => //code here
}
}
关于Scala 匹配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5000376/