Reputation: 10311
I am working through the (admittedly somewhat old) Programming Scala [Subramaniam, 2009] and encountered a troubling compiler warning when working through section 9.7 "Matching using case classes" (see below).
Here is the solution I devised based on my interpretation of the error message. How could I improve upon this code with a solution closer to the original intent of the book's example? Particularly if I wanted to use sealed
case class functionality?
/**
* [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
}
Upvotes: 1
Views: 1312
Reputation: 467
Inherit from a "sealed trait Trade" instead.
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
Upvotes: 4