Scala 递归隐式参数
想象一下下面的代码:Scala 递归隐式参数,scala,implicit,Scala,Implicit,想象一下下面的代码: trait Converter[T] { def convert(value: String): T } object Converter { implicit val intConverter: Converter[Int] = value => value.toInt implicit def optionConverter[T]: Converter[Option[T]] = new OptionConverter[T] } class Opti
trait Converter[T] {
def convert(value: String): T
}
object Converter {
implicit val intConverter: Converter[Int] = value => value.toInt
implicit def optionConverter[T]: Converter[Option[T]] = new OptionConverter[T]
}
class OptionConverter[T](implicit val ev: Converter[T]) extends Converter[Option[T]] {
...
}
正如您所看到的,OptionConverter
为其包含的类型接收了一个Converter[T]
,但编译器会抱怨,因为当它试图编译OptionConverter
时,它不知道类型
我想这可能已经解决了…但我想不出一个解决方案
有什么想法吗?您可以接受包装的
转换器作为选项转换器
方法的隐式参数:
implicit def optionConverter[T](implicit ev: Converter[T]): Converter[Option[T]] = new OptionConverter[T]
或速记:
implicit def optionConverter[T : Converter]: Converter[Option[T]] = new OptionConverter[T]
您可以只接受包装的转换器
作为选项转换器
方法的隐式参数:
implicit def optionConverter[T](implicit ev: Converter[T]): Converter[Option[T]] = new OptionConverter[T]
或速记:
implicit def optionConverter[T : Converter]: Converter[Option[T]] = new OptionConverter[T]