以下示例来自"Programming in Scala"一书.给定一个类'Rational'和以下方法定义:
def add(that: Rational): Rational =
new Rational(
this.numer * that.denom + that.numer * this.denom,
this.denom * that.denom
)
Run Code Online (Sandbox Code Playgroud)
我可以使用带有Int参数的便捷版本成功地重载add方法,并使用上面的定义:
def add(that: Int): Rational =
add(new Rational(that, 1))
Run Code Online (Sandbox Code Playgroud)
到目前为止没问题.
现在,如果我将方法名称更改为运算符样式名称:
def +(that: Rational): Rational =
new Rational(
this.numer * that.denom + that.numer * this.denom,
this.denom * that.denom
)
Run Code Online (Sandbox Code Playgroud)
像这样过载:
def +(that: Int): Rational =
+(new Rational(that, 1))
Run Code Online (Sandbox Code Playgroud)
我得到以下编译错误:
(fragment of Rational.scala):19: error: value unary_+ is not a member of this.Rational
+(new Rational(that, 1))
^
Run Code Online (Sandbox Code Playgroud)
为什么编译器要查找该+ …
scala ×1