案例类继承弃用的更好解决方案



我正在学习(诚然有点老)编程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
}

改为从"密封特征交易"继承。

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

最新更新