我問了一個earlier question我收到了很好的答案。在評論中,Travis提到,比較兩個不會直接工作,但可以使用模式匹配來確保比較同一個類。Scala:解決不明確的模式匹配類型
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) = { ... }
}
在嘗試模式匹配下面,我有我懷疑有使用HandValue[_]
做一個編譯時錯誤。 val h1: HandValue[T <: HandValue[T]]
,類似於聲明的類型,無效。有沒有辦法解決這些問題?
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..
}
}
}
編輯:編譯時錯誤是:
error: type arguments [_$3] do not conform to class HandValue's type parameter bounds [T <: euler.solutions.p54.HandValue[T]]
(h1, h2) match {
編輯2:如this question提到的,使用Type[_]
將無法正常工作。
什麼是編譯時錯誤? – pedrofurla 2012-08-06 02:07:01
對不起,很好的電話!我忘了粘貼它。 – Louis 2012-08-06 02:08:27
順便說一下,Hand和HandValue之間的關係是什麼? – pedrofurla 2012-08-06 03:29:29