我正在使用以下用 Scala 2.11.8 编写的代码:
sealed trait Acceptable[T]
object Acceptable {
implicit object Int extends Acceptable[Int]
implicit object String extends Acceptable[String]
}
case class Enc[T](f: T => Any)
implicit def test[I, T](implicit f: I => T, a: Acceptable[T]): Enc[I] =
Enc[I](f)
val e = implicitly[Enc[Int]]
它成功编译。
如您所见,a: Acceptable[T]
参数应该很容易转换为上下文绑定:
implicit def test[I, T: Acceptable](implicit f: I => T): Enc[I] =
Enc[I](f)
但是在那之后,编译开始失败并出现错误:
找不到参数 e 的隐式值:app.Enc[Int]
为什么会这样?
更新:
我尝试-Xlog-implicits
了编译器选项,编译日志给了我:
[info] /path/to/ScalaTest/src/main/scala/app/Main.scala:60: test is not a valid implicit value for app.Enc[Int] because:
[info] hasMatchingSymbol reported error: ambiguous implicit values:
[info] both object Int in object Acceptable of type app.Acceptable.Int.type
[info] and object String in object Acceptable of type app.Acceptable.String.type
[info] match expected type app.Acceptable[T]
[info] val e = implicitly[Enc[Int]]
[info] ^
[info] /path/to/ScalaTest/src/main/scala/app/Main.scala:60: app.test is not a valid implicit value for app.Enc[Int] because:
[info] hasMatchingSymbol reported error: ambiguous implicit values:
[info] both object Int in object Acceptable of type app.Acceptable.Int.type
[info] and object String in object Acceptable of type app.Acceptable.String.type
[info] match expected type app.Acceptable[T]
[info] val e = implicitly[Enc[Int]]
[info] ^
[error] /path/to/ScalaTest/src/main/scala/app/Main.scala:60: could not find implicit value for parameter e: app.Enc[Int]
[error] val e = implicitly[Enc[Int]]
好的,我理解这个输出。但是为什么它在隐式参数的情况下起作用?