Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带有选项类型的Scala模式匹配_Scala_Pattern Matching - Fatal编程技术网

带有选项类型的Scala模式匹配

带有选项类型的Scala模式匹配,scala,pattern-matching,Scala,Pattern Matching,我试图用以下定义定义二叉树: trait Node { val label: Int } case class BranchNode(override val label: Int, left: Option[Node], right: Option[Node]) extends Node case class LeafNode(override val label: Int) extends Node 然后使用Scala的模式匹配定义一个简单的printTree方法,

我试图用以下定义定义二叉树:

  trait Node {
    val label: Int
  }
  case class BranchNode(override val label: Int, left: Option[Node], right: Option[Node]) extends Node
  case class LeafNode(override val label: Int) extends Node
然后使用Scala的模式匹配定义一个简单的
printTree
方法,如下所示:

  def printTree(aTree: Option[Node]): Unit = aTree match {
    case None => print(".")
    case Some(LeafNode(label)) => print(label)
    case Some(BranchNode(label, left, right)) => "{" + printTree(left) + label + printTree(right) + "}"
  }

Intellij IDE警告我,匹配可能并不详尽。
选项
的值可以是
None
Some
。在
选项[Node]
的情况下,它可以是
Some(LeafNode)
Some(BranchNode)
。我还忽略了哪些情况?

因为你的特质没有被密封,它可以在不同的包中扩展。IntelliJ警告您,将来任何扩展此特性并忘记实施额外的
案例的人都可能会导致
匹配错误
。如果要限制其扩展,请使用:

sealed trait Node

这肯定是一个编译器警告,请参见下面我正在破坏您的代码,通过传递
printree(选项(IWillBreakYou(2))

原因是您选择了
选项[Node]
,任何人都可以扩展
节点(包内/包外,除非受保护),而您在比赛中没有考虑到这一点

因此,添加故障保护匹配
案例将修复未来的错误

def printTree(aTree: Option[Node]): Unit = aTree match {
        case None => print(".")
        case Some(LeafNode(label)) => print(label)
        case Some(BranchNode(label, left, right)) => "{" + printTree(left) + label + printTree(right) + "}"
        case _ => println("do nothing")
 }
def printTree(aTree: Option[Node]): Unit = aTree match {
        case None => print(".")
        case Some(LeafNode(label)) => print(label)
        case Some(BranchNode(label, left, right)) => "{" + printTree(left) + label + printTree(right) + "}"
        case _ => println("do nothing")
 }