递归隐式参数

Recursive implicit parameter

想象一下下面的代码:

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 时,它不知道类型.

我想这可能已经解决了...但我想不出解决方案。

有什么想法吗?

您可以只接受包装的 Converter 作为 optionConverter 方法的隐式参数:

implicit def optionConverter[T](implicit ev: Converter[T]): Converter[Option[T]] = new OptionConverter[T]

或者 shorthand:

implicit def optionConverter[T : Converter]: Converter[Option[T]] = new OptionConverter[T]