带有选项类型的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")
}