我有一些类型:
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
...
吗?
答案 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]