I have
trait OptionTransaction {
def data: Data
}
BuyOptionTransaction extends OptionTransaction
SellOptionTransaction extends OptionTransaction
I use these with a Formatter type class to create string representations of various transactions
trait Formatter[T] {
def format(ot:T):String
}
object Formatter {
def apply[T](implicit screen: Formatter[T]) = screen
implicit val buyOT = new Formatter[BuyOptionTransaction] {
def format(ot: BuyOptionTransaction):String = ot.x.toString
}
implicit val sellOT = new Formatter[SellOptionTransaction] {
def format(ot: SellOptionTransaction):String = ot.y.toString
}
}
This is the entry point:
import Formatter._
val closeTransactions: List[OptionTransaction] = ...
closeTransactions.map(startFormat)
The problem is that closeTransactions
has type List[OptionTransaction]
and the type class needs OptionTransaction
downcast to BuyOptionTransaction
or SellOptionTransaction
otherwise it won't find the implicit formatter.
How can I achieve this downcast automatically?