这是一个简单的复制器,我在其中定义了一个带有隐式重新排序转换的“可交换”对类型。f
如果函数的参数在预先存在的命名值中(t
在示例中),则编译器将按预期应用隐式转换。但是,如果我尝试f
直接调用 literal CommutativePair
,它会失败并出现类型错误。在这种情况下,编译器不会应用隐式重新排序转换。
object repro {
import scala.language.implicitConversions
case class CommutativePair[A, B](a: A, b: B)
object CommutativePair {
// Support a kind of commutative behavior via an implicit reordering
implicit def reorderPair[B, A](pair: CommutativePair[B, A]) =
CommutativePair(pair.b, pair.a)
}
// The idea is to allow a call to 'f' with Pair[Int, String] as well,
// via implicit reorder.
def f(p: CommutativePair[String, Int]) = p.toString
val t = CommutativePair(3, "c")
// This works: the implicit reordering is applied
val r1 = f(t)
// This fails to compile: the implicit reordering is ignored by the compiler
val r2 = f(CommutativePair(3, "c"))
}