Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 隐式替代_Scala_Implicit - Fatal编程技术网

Scala 隐式替代

Scala 隐式替代,scala,implicit,Scala,Implicit,我有一些类型: 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可以是定义了隐式值的任何类型?也

我有一些类型:

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
可以是定义了隐式值的任何类型?也就是说,每当我有
隐式vala:OutputHandler[TypeA]
等时,我可以调用
进程(List(TypeA())
进程(List(TypeB())
吗?

您可以通过返回
OutputHandler[List[a]]
隐式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]