【发布时间】:2016-11-02 19:09:03
【问题描述】:
我正在阅读 Debasish Ghosh 的新书《函数式和反应式域建模》,我真的很喜欢它。
第 5 章中让我感到困惑的一件事是下面这行:
Reporting.report(accts).foreach(println _)
可以获取 Seq[Account] 并将其转换为 Seq[Show]。我知道隐式在起作用,但是编译器采取了哪些步骤来允许它编译?这只是更一般的隐含规则的一个特定实例吗? 似乎编译器正在将 Show trait 混合到 Account 对象中。谢谢!
改编自第 164 页:
import scala.util.Try
trait Show[T] {
def shows(t: T): Try[String]
}
trait ShowProtocol {
implicit val showAccount: Show[Account]
implicit val showCustomer: Show[Customer]
}
trait DomainShowProtocol extends ShowProtocol {
override implicit val showAccount: Show[Account] = (t: Account) => Try("Account")
override implicit val showCustomer: Show[Customer] = (t: Customer) => Try("Customer")
}
case class Account()
case class Customer()
object Reporting {
def report[T: Show](as: Seq[T]): Seq[Try[String]] = as.map(implicitly[Show[T]].shows _)
}
object DomainShowProtocol extends DomainShowProtocol
object Main {
def main(args: Array[String]): Unit = {
import DomainShowProtocol._
val accts: Seq[Account] = Seq(
Account(),
Account(),
Account()
)
Reporting.report(accts).foreach(println _)
}
}
【问题讨论】: