下铸造的类型类Scala中
我下铸造的类型类Scala中
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
否则它将不会找到隐式格式化程序。
我该如何自动实现这种下降?
回答:
可以collect
相应类型:
val closeTransactions: List[OptionTransaction] = ??? val buys = closeTransactions.collect { case b: BuyOptionTransaction => b}
val sells = closeTransactions.collect { case s: SellOptionTransaction => s}
现在你可以应用适当的类型类。
将动作/转换添加到OptionTransaction
特征并将其用于动态绑定可能会更好。如果您想继续为其中一个人工作,请查看this answer。
回答:
如果您想要处理多态运行时,您需要实现某种动态(运行时)调度,而不是类型类,它们是静态的(编译时)。它可能看起来像这样:
type Data = String trait OptionTransaction {
def data: Data = ""
}
class BuyOptionTransaction extends OptionTransaction {
def x: String = "X"
}
class SellOptionTransaction extends OptionTransaction {
def y: String = "Y"
}
trait Formatter[T] {
def format(ot:T):String
}
object Formatter {
def apply[T](implicit screen: Formatter[T]) = screen
def selectFormatter[T](obj: T)(implicit formatter: Formatter[T]) = formatter
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
}
implicit val ot = new Formatter[OptionTransaction] {
def format(ot: OptionTransaction):String = ot match {
case ot: BuyOptionTransaction =>
selectFormatter(ot).format(ot)
case ot: SellOptionTransaction =>
selectFormatter(ot).format(ot)
}
}
}
def startFormat[T](ot: T)(implicit ev: Formatter[T]) = {
ev.format(ot)
}
import Formatter._
val closeTransactions: List[OptionTransaction] = List(new BuyOptionTransaction, new SellOptionTransaction)
closeTransactions.map(startFormat(_))
以上是 下铸造的类型类Scala中 的全部内容, 来源链接: utcz.com/qa/257799.html