I asked an earlier question to which I received a great answer. In the comments, Travis mentioned that comparing two HandValue
s wouldn't work directly, but pattern matching could be used to ensure comparing the same class.
sealed abstract class HandValue[T <: HandValue[T]](val rank: Int) extends Ordered[T]
case class HighCard(high: Int) extends HandValue[HighCard](0){
def compare(that: HighCard) = this.high - that.high
}
case class TwoPair(high: Int, big: Int, sm: Int) extends HandValue[TwoPair](2) {
def compare (that: TwoPair) = { ... }
}
In the attempted pattern matching below, I have a compile-time error that I suspect has to do with using HandValue[_]
. val h1: HandValue[T <: HandValue[T]]
, similar to how the type was declared, isn't valid. Is there a way to resolve these?
val ans = sessions count {
hands: (Hand, Hand) => {
val h1: HandValue[_] = handValue(hands._1)
val h2: HandValue[_] = handValue(hands._2)
(h1, h2) match { // <-- Line as source of error
case _ if h1.rank > h2.rank => true
case (a: HighCard, b: HighCard) => a > b
case (a: TwoPair, b: TwoPair) => a > b
// etc..
}
}
}
Edit: The compile-time error is:
error: type arguments [_$3] do not conform to class HandValue's type parameter bounds [T <: euler.solutions.p54.HandValue[T]]
(h1, h2) match {
Edit 2: As mentioned in this question, using Type[_]
won't work.