Scala模式与Option类型匹配

sha*_*aan 2 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
Run Code Online (Sandbox Code Playgroud)

然后printTree使用Scala的模式匹配定义一个简单的方法,如下所示:

  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) + "}"
  }
Run Code Online (Sandbox Code Playgroud)

Intellij IDE警告我,这场比赛可能并非详尽无遗.一个Option可以拥有NoneSome作为它的价值观.如果是Option[Node],它可以是Some(LeafNode)Some(BranchNode).还有什么其他情况我可以忽略?

Yuv*_*kov 6

由于您的特性不是sealed,因此可以在不同的包中进行扩展.IntelliJ警告你未来有可能延长这个特性而忘记实施额外的特性case可能导致a MatchError.如果要限制其扩展名,请使用:

sealed trait Node
Run Code Online (Sandbox Code Playgroud)