Reputation: 1011
I created a ComplexNumber
class. I would like to be able to do something like
val c = ComplexNumber(1,3);
3 * c;
but that would require overloading *
for int, double, etc. Is this possible?
Upvotes: 0
Views: 170
Reputation: 51271
You need to define an implicit conversion for each type you want to operate on. A convenient place for this is in the companion object.
object ComplexNumber {
import scala.language.implicitConversions
implicit def i2cn(i:Int):ComplexNumber = new ComplexNumber(....
}
Now 3 * c
will work as long as the *
method is defined as part of the ComplexNumber
class.
class ComplexNumber(a:Int, b:Int) {
def *(cn:ComplexNumber): ComplexNumber = ...
}
Upvotes: 4