I have a customized compare
methods that takes two parameters. One of them are expected to be implicitly convertible to another:
object Test extends App {
def compare[T1, T2](a: T1, b: T2)(implicit ev: T1 => T2) = compareImpl[T2](ev(a), b)
def compare[T1, T2](a: T1, b: T2)(implicit ev: T2 => T1) = compareImpl[T1](a, ev(b))
def compareImpl[T](a: T, b: T) = a == b
case class Foo(s: String)
case class Bar(s: String)
implicit def foo2bar(f: Foo): Bar = Bar(f.s)
println(compare(Foo("hello"), Bar("hello")))
}
However this snippet gives me error:
error: ambiguous reference to overloaded definition,
both method compare in object Test of type [T1, T2](a: T1, b: T2)(implicit ev: T2 => T1)Boolean
and method compare in object Test of type [T1, T2](a: T1, b: T2)(implicit ev: T1 => T2)Boolean
match argument types (Test.Foo,Test.Bar) and expected result type Any
implicit def foo2bar(f: Foo): Bar = Bar(f.s)
If I remove the second compare
, it works, but then if I do compare(Bar("hello), Foo("hello"))
it won't compile.
How can I have these two versions without ambiguity?
compare(1, "1")
And there are bothInt => String
&String => Int
. IMHO, too much magic is problematic here. – Hartz