是否可以重载 scala 中原始数字类型的运算符?

Is it possible to overload the operators for the primitive numeric types in scala?

我创建了一个 ComplexNumber class。我希望能够做类似

的事情

val c = ComplexNumber(1,3); 3 * c;

但这需要为 int、double 等重载 *。这可能吗?

您需要为每个要操作的类型定义一个隐式转换。一个方便的地方是在伴随对象中。

object ComplexNumber {
  import scala.language.implicitConversions
  implicit def i2cn(i:Int):ComplexNumber = new ComplexNumber(....
}

现在,只要 * 方法定义为 ComplexNumber class.

的一部分,3 * c 就会起作用
class ComplexNumber(a:Int, b:Int) {
  def *(cn:ComplexNumber): ComplexNumber = ...
}