我想要这个匹配两个案例类的比较函数,但它有点冗长。
叶子总是在列表中排序。
abstract class CodeTree
case class Fork(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree
case class Leaf(char: Char, weight: Int) extends CodeTree
def sortCodeTreeFun(x: CodeTree, y: CodeTree) = {
(x, y) match {
case (x1: Leaf, y1: Leaf) => true
case (x1: Fork, y1: Leaf) => x1.weight < y1.weight
case (x1: Leaf, y1: Fork) => x1.weight < y1.weight
case (x1: Fork, y1: Fork) => x1.weight < y1.weight
}
}
我试图将 CodeTree 构造函数修改为:
abstract class CodeTree(weight: Int)
这样我就可以直接比较 x 和 y,但是编译器说:
“构造函数 CodeTree 的参数不足:(权重:Int)patmat.Huffman.CodeTree”
还有另一种缩短 sortCodeTreeFun 方法的方法吗?