假设我有一个简单abstract BinaryTree的子类Node,Leaf我想写一个产生一个的函数List[Leaf].
def getLeaves(tree: BinaryTree): List[Leaf] =
tree match {
case Leaf(v) => List(tree.asInstanceOf[Leaf])
case Node(left, right) => getLeaves(left) ++ getLeaves(right)
}
Run Code Online (Sandbox Code Playgroud)
有没有办法避免案件中的明确asInstanceOf[Leaf]演员?如果我把它遗漏,我得到一个诊断说法:发现:BinaryTree; 需要叶.Leaf
我在其他地方看过这个结构.它似乎做了这个工作.
def getLeaves(tree: BinaryTree): List[Leaf] =
tree match {
case leaf: Leaf => List(leaf)
case Node(left, right) => getLeaves(left) ++ getLeaves(right)
}
Run Code Online (Sandbox Code Playgroud)