scala - Better solution to case class inheritance deprecation? -
i working through (admittedly old) programming scala [subramaniam, 2009] , encountered troubling compiler warning when working through section 9.7 "matching using case classes" (see below).
here solution devised based on interpretation of error message. how improve upon code solution closer original intent of book's example? particularly if wanted use sealed
case class functionality?
/** * [warn] case class `class sell' has case ancestor `class trade'. * case-to-case inheritance has potentially dangerous bugs * unlikely fixed. encouraged instead use * extractors 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 }
inherit "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
Comments
Post a Comment