hielsnoppe
hielsnoppe

Reputation: 2869

Type restricting trait methods depending on instance class

Is it possible to restrict a method defined in a trait to a certain type depending on the extending class? For example:

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
}

This way a MarksScore(true) is comparable to a RankingScore(5) which is nice, but meaningless. So I would like to restrict compare to just objects of the respective class in contrast to all implementers of Score.

Upvotes: 1

Views: 56

Answers (1)

hielsnoppe
hielsnoppe

Reputation: 2869

Something about this does not feel right, but it achieves what I asked for:

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
}

Upvotes: 1

Related Questions