Scala 匹配错误 [英] Scala match error
问题描述
我尝试用匹配项替换我的 isInstanceOf 检查,但它不起作用.
I tried to replace my isInstanceOf check with a match, but it does not work.
在我的方法中,我检查树节点 - 如果它是叶子 - 我想立即将它返回到 Vector 中,如果不是 - 我继续使用该方法.
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.
原来我有:
//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
但我得到了 scala.MatchError.
but I get scala.MatchError.
推荐答案
如果您的 common
不是 LeafNode,您将收到
MatchError
代码>.您的 if
和 match
表达式是不等价的.我认为使它们等效的最直接方法是:
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 _ =>
}
但我建议查看整个代码块并找出更实用的方法来完成这项工作.也就是说,中间没有 return
.记住 match 是一个表达式,所以这样的事情可能是可能的:
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
}
}
这篇关于Scala 匹配错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!