隐含替代

时间:2017-08-08 14:39:42

标签: scala implicit

我有一些类型:

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

采用隐式参数的方法:

implicit val handler = new OutputHandler[TypeA] {}

定义为的值:

List[T]

如何创建T的通用隐式值,其中process(List(TypeA()))可以是任何定义了隐式值的类型?也就是说,只要有process(List(TypeB())等,我就可以致电implicit val a: OutputHandler[TypeA]1.1 1.6 1.4 1.9 1.12 ... 吗?

1 个答案:

答案 0 :(得分:2)

您可以使用implicit def返回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]