trait OptionTransaction {
def data: Data
}
BuyOptionTransaction extends OptionTransaction
SellOptionTransaction extends OptionTransaction
我使用这些有格式类型的类来创建各种交易
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
}
}
的字符串表示这是切入点:
import Formatter._
val closeTransactions: List[OptionTransaction] = ...
closeTransactions.map(startFormat)
问题是closeTransactions
有类型List[OptionTransaction]
和类型类需要OptionTransaction
downcast到BuyOptionTransaction
或SellOptionTransaction
否则它将不会找到隐式格式化程序。
我该如何自动实现这种下降?
您可以更改'OptionTransaction'及其派生类的定义吗?通常情况下,可以将抽象的'format'添加到'OptionTransaction'并在派生类中根据需要实现它,从而获得非常简单和高效的解决方案。 – Suma
如果我对我很熟悉......我想我已经回答了一个类似的问题,以便可以将其标记为重复:[通过隐式证据获取运行时类型](https://stackoverflow.com/questions/ 42292338/get-runtime-type-by-implicit-evidence/42293934#42293934) – Suma