1

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) = ...
    }
4

1 に答える 1

3

F境界ポリモーフィズムは、この種のことを達成するための一般的な方法の 1 つです。

sealed abstract class HandValue[A <: HandValue[A]](rank: Int) extends Ordered[A]

case class HighCard(high: Int) extends HandValue[HighCard](0){
    def compare(that: HighCard) = ...
}

case class TwoPair(high: Int, big: Int, sm: Int) extends HandValue[TwoPair](2) {
    def compare(that: TwoPair) = ...
}

拡張しようとしているものの型パラメーターとして自分自身を渡さなければならないというのは、定型句のように感じるかもしれませんが、親のサブクラス型について具体的に話すことができる非常に便利な方法です。

于 2012-08-05T21:19:32.950 に答える