用隐式定义“隐式 def”?

Defining `implicit def` w/ Implicit?

鉴于:

trait Foo[A]
class B

然后是下面的implicit def

implicit def f[A](b: B)(implicit ev: Foo[A]): String = "foo"

我试图隐式解析 B => String,但编译失败:

scala> implicitly[B => String]
<console>:15: error: No implicit view available from B => String.
       implicitly[B => String]
                 ^

我猜 implicit Foo[A] 在我对 B => String.

的隐含解决方案中可以说是出问题了

如何调整 implicitly 的参数,即 B => String,以便上面的编译?

使用类型类而非隐式转换的类似代码:

trait MyFunT[A] extends (A => String)

object MyFunT {
  /**Factory to easily define an instance from a fun */
  def apply[A](f: A => String): MyFunT[A] = new MyFunT[A] {
    def apply(a: A): String = f(a)
  }
}

implicit def foo[A](implicit ev: Foo[A]) = MyFunT[A] { a: A => /* do something with `a` and `ev` */ "foo" }

Even if implicits based/requiring other implicit are usual, I would advice to take care not to have "too long chain" about that.