是否可以根据扩展类将特征中定义的方法限制为某种类型?例如:
trait Score extends Ordered[Score] {
val reducedValue: Float // must be implemented by extending classes
def compare (that: Score): Int = this.reducedValue.compare(that.reducedValue)
}
case class MarksScore (set: Boolean) extends Score {
val reducedValue = if (this.set) 1.0f else 0.0f
}
case class RankingScore (rank: Float) extends Score {
val reducedValue = this.rank
}
这样MarksScore(true)
与RankingScore(5)
相当,这很好,但没有意义。所以我想将compare
限制为相应类的对象,而不是Score
的所有实现者。
答案 0 :(得分:1)
关于这一点感觉并不正确,但它实现了我的要求:
trait Score[T <: Score[T]] extends Ordered[T] {
val reducedValue: Float
def compare (that: T): Int = this.reducedValue.compare(that.reducedValue)
}
case class MarksScore (set: Boolean) extends Score[MarksScore] {
val reducedValue = if (this.set) 1.0f else 0.0f
}
case class RankingScore (rank: Float) extends Score[RankingScore] {
val reducedValue = this.rank
}