Scala 匹配错误

标签 scala

我尝试用匹配项替换 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。您的 ifmatch 表达式并不等效。我认为使它们等效的最直接方法是:

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/

相关文章:

scala - 当我想要构建功能模块创建时如何处理 Vec 输入

IntelliJ 中的 scala spark notebook

scala - "generics"在 Scala 中?

scala - 类似于 Python 字典的适当 Scala 集合

regex - Scala 检查字符串是否不包含特殊字符

scala - 我的 Scala 代码虽然通过了 @tailrec,但没有获得 TCO

scala - 使用 json4s 序列化带有特征混合的案例类

arrays - 从 Spark SQL 中的字符串列表创建文字和列数组

scala - 如何在 scalaz 7 中使用变压器在 monad 堆栈之间进行转换

java - Scala如何获取其JVM环境?