I’m trying to compare poker hands as shown below. I’ve been playing around with different type operators but would be interested in some guidance. My goal is to have an abstract parent class that declares Ordered (so that it doesn’t need to be declared on each subclass), but the parameterization would be such that each subclass can only be compared with an instance of the same class.
For example, below, a HighCard can only be compared with another HighCard, TwoPair with another TwoPair, etc.
sealed abstract class HandValue(rank: Int) extends Ordered[?]
case class HighCard(high: Int) extends HandValue(0){
def compare(that: HighCard) = ...
}
case class TwoPair(high: Int, big: Int, sm: Int) extends HandValue(2) {
def compare(that: TwoPair) = ...
}
F-bounded polymorphism is one common way to accomplish this kind of thing:
It may feel a bit like boilerplate to have to hand yourself as a type parameter to the thing you’re extending, but it’s a very convenient way to be able to talk specifically about subclass types in the parent.