我有几种类型:
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] {}在T可以是任何定义了隐式值的类型的情况下,如何创建List[T]的泛型隐式值?也就是说,每当我有implicit val a: OutputHandler[TypeA]时,我是否可以调用process(List(TypeA()))或process(List(TypeB()),等等?
发布于 2017-08-09 00:13:36
您可以通过返回OutputHandler[List[A]]的implicit def来实现这一点
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]https://stackoverflow.com/questions/45571323
复制相似问题