我正在研究(诚然有些老)Programming Scala [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
}