定义了扩展 Ordering[A] 的类 A 和 A 的子类 B,如何自动对 B 数组进行排序?Scala 编译器抱怨它“找不到参数 ord: Ordering[B] 的隐含值”。这是一个具体的 REPL 示例(Scala 2.8),其中 A = Score 和 B = CommentedScore:
class Score(val value: Double) extends Ordered[Score] {
def compare(that: Score) = value.compare(that.value)
}
defined class Score
trait Comment { def comment: String }
defined trait Comment
class CommentedScore(value: Double, val comment: String) extends Score(value) with Comment
defined class CommentedScore
val s = new CommentedScore(10,"great")
s: CommentedScore = CommentedScore@842f23
val t = new CommentedScore(0,"mediocre")
t: CommentedScore = CommentedScore@dc2bbe
val commentedScores = Array(s,t)
commentedScores: Array[CommentedScore] = Array(CommentedScore@b3f01d, CommentedScore@4f3c89)
util.Sorting.quickSort(commentedScores)
error: could not find implicit value for parameter ord: Ordering[CommentedScore]
util.Sorting.quickSort(commentedScores)
^
我该如何解决这个问题(也就是说,“免费”对 Array[B] = Array[CommentedScore] 进行排序,因为我知道如何对 Array[A] = Array[Score] 进行排序),以一种避免样板的优雅方式?
谢谢!