2013-08-07 30 views
1

我正在通過(確實有點老)編程斯卡拉 [Subramaniam,2009],並通過第9.7節「匹配使用案例類」(見下文)時遇到了令人不安的編譯器警告。更好地解決案例類繼承棄用問題?

這是我根據我對錯誤消息的解釋設計的解決方案。我怎樣才能用這個解決方案來改進這個代碼呢?這個解決方案更接近本書例子的原意?特別是如果我想使用sealed案例類功能?

/** 
* [warn] case class `class Sell' has case ancestor `class Trade'. 
* Case-to-case inheritance has potentially dangerous bugs which 
* are unlikely to be fixed. You are strongly encouraged to instead use 
* extractors to pattern match on non-leaf nodes. 
*/ 

// abstract case class Trade() 
// case class Buy(symbol: String, qty: Int) extends Trade 
// case class Sell(symbol: String, qty: Int) extends Trade 
// case class Hedge(symbol: String, qty: Int) extends Trade 

object Side extends Enumeration { 
    val BUY = Value("Buy") 
    val SELL = Value("Sell") 
    val HEDGE = Value("Hedge") 
} 

case class Trade(side: Side.Value, symbol: String, qty: Int) 

def process(trade: Trade) :String = trade match { 
    case Trade(_, _, qty) if qty >= 10000 => "Large transaction! " + trade 
    case Trade(_, _, qty) if qty % 100 != 0 => "Odd lot transaction! " + trade 
    case _ => "Standard transaction: " + trade 
} 
+0

嗯...似乎有幾本書的標題爲「Programming Scala」。參考Subramaniam的 – noahlz

+1

然後有* Scala *編程,Odersky的經典。 – sourcedelica

回答

4
從 「密封特質貿易」,而不是

繼承。

sealed trait Trade 
case class Buy(symbol: String, qty: Int) extends Trade 
case class Sell(symbol: String, qty: Int) extends Trade 
case class Hedge(symbol: String, qty: Int) extends Trade