First, what works:
object Test extends App {
trait T[R] {
def make(n: Int): R
}
class A(x: Int) extends T[A] {
def make(n: Int) = new A(n)
}
class B(x: Int) extends T[B] {
def make(n: Int) = new B(n)
}
implicit class Conv(n: Int) {
def +[X <: T[X]](t: X): X = t.make(n)
def *[X <: T[X]](t: X): X = t.make(n)
}
val a: A = 1 + new A(2)
val b: B = 1 * new B(2)
}
I have two implementations A
and B
of the same trait T
and an implicit conversion so +
and *
on Int
s can take an A
or a B
.
This, however, does not work:
implicit class Conv[X <: T[X]](n: Int) {
def +(t: X): X = t.make(n)
def *(t: X): X = t.make(n)
}
I’m unable to decipher the error message:
Information:(39, 14) Conv is not a valid implicit value for Int(1) => ?{def +(x$1: ? >: Test.A): Test.A} because:
incompatible: (n: Int)Test.Conv[X] does not match expected type Int(1) => ?{def +(x$1: ? >: Test.A): Test.A}
val a: A = 1 + new A(2)
Furthermore, the second approach (type-parametrized class instead of methods) does work if the methods are named ++
and **
instead of +
and *
!
Anyone has a light to shine on this?
MC