I want to write a class which can work nicely with numbers and operators, so I want to know how to overload an operator when the left hand argument is a built-in type or other value for which I can't modify the implementation.
class Complex(val r:Double,val i:Double){
def +(other:Complex) = new Complex(r+other.r,i+other.i)
def +(other:Double) = new Complex(r+other,i)
def ==(other:Complex) = r==other.r && i==other.i
}
With this example, the following works:
val c = new Complex(3,4)
c+2 == new Complex(5,4) //true
But I also want to be able to write
2+c
which doesn't work as Int.+
can't accept an argument of type Complex
.
Is there a way to let me write this and have it work as I want?
I've found out about right associative methods, but they seem to require a different operator name.