隐式替换

Implicit substitution

我有一些类型:

trait OutputHandler[A]

case class TypeA()

case class TypeB()

采用隐式参数的方法:

def process[A](a: Any => A)(implicit handler: OutputHandler[A]) {}

定义为的值:

implicit val handler = new OutputHandler[TypeA] {}

如何创建 List[T] 的通用隐式值,其中 T 可以是任何定义了隐式值的类型?也就是说,我可以在有 implicit val a: OutputHandler[TypeA] 时调用 process(List(TypeA()))process(List(TypeB()) 等吗?

您可以通过 implicit def returns OutputHandler[List[A]]:

implicit val handler = new OutputHandler[TypeA] {}

implicit def listOf[A](implicit ev: OutputHandler[A]): OutputHandler[List[A]] = new OutputHandler[List[A]] {
  // can implement this output handler using ev: OutputHandler[A]
}

process(t => List(TypeA())) // compiles, because OutputHandler[TypeA] exists
process(t => List(TypeB())) // does not compile, as expected, because there's no OutputHandler[TypeB]