我正在完成(通常有点旧) Programming Scala [Subramaniam,2009]并且在完成第9.7节“使用案例类匹配”(见下文)时遇到了令人不安的编译器警告。 / p>
这是我根据对错误消息的解释而设计的解决方案。如何使用更接近本书示例原始意图的解决方案来改进此代码?特别是如果我想使用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 :(得分: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