问题描述
我想要这个匹配两个 case 类的比较函数,但它有点冗长.
I want to have this comparison function that matches two case classes, but it's a bit verbose.
叶子总是按照列表中的排序顺序.
Leafs are always in the sorted order in the List.
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 构造函数修改为:
I tried to modify CodeTree constructor to be:
abstract class CodeTree(weight: Int)
这样我就可以直接比较 x 和 y,但是编译器说:
So that I can compare x and y directly, but compiler says:
构造函数 CodeTree 的参数不足:(weight: Int)patmat.Huffman.CodeTree"
还有其他方法可以缩短 sortCodeTreeFun 方法吗?
Is there another way to shorten sortCodeTreeFun method?
推荐答案
你可以简单地说:
def sortCodeTreeFun(x: CodeTree, y: CodeTree) = {
(x, y) match {
case (_: Leaf, _: Leaf) => true
case (x1: CodeTree, y1: CodeTree) => x1.weight < y1.weight
}
}
并将抽象类CodeTree定义为
And define abstract class CodeTree as
abstract class CodeTree {
def weight: Int
}
错误的原因是当你扩展一个带参数的类时,你需要提供参数.所以对于
The reason for the error is that when you extend an class that take a parameter you need to supply the parameter. So for
abstract class CodeTree(weight: Int)
您需要将其扩展为
case class Fork(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree(weight)
这就是你得到的错误所说的:
That's what the error you were getting was saying:
"not enough arguments for constructor CodeTree: (weight: Int)"
这是因为您在扩展 CodeTree 时没有提供所需的参数 weight
.
It was because you weren't supplying the required argument weight
when extending CodeTree.
但是这种方法的问题是权重不是 CodeTree 的成员,因此不能从 CodeTree 类型的实例访问.也就是说,如果你这样做了:
The problem with this approach though is that weight is not a member of CodeTree and hence can not to be accessed from an instance of type CodeTree. That is to say, if you did:
scala> Fork(...).asInstanceOf[CodeTree].weight
<console>:11: error: value weight is not a member of CodeTree
因此,在您的模式匹配中,您将无法执行 x1.weight
,因为 x1 的类型是 CodeTree
和 CodeTree
没有 weight
.
So, in your pattern match, you wouldn't be able to do x1.weight
since the type of x1 is a CodeTree
and CodeTree
does not have a weight
.
这篇关于Scala 中的案例类匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!