【发布时间】:2010-12-31 18:22:12
【问题描述】:
以下示例来自《Scala 编程》一书。给定一个“Rational”类和以下方法定义:
def add(that: Rational): Rational =
new Rational(
this.numer * that.denom + that.numer * this.denom,
this.denom * that.denom
)
我可以使用带有 Int 参数的便捷版本成功地重载 add 方法,并且使用上面的定义:
def add(that: Int): Rational =
add(new Rational(that, 1))
目前没有问题。
现在,如果我将方法名称更改为运算符样式名称:
def +(that: Rational): Rational =
new Rational(
this.numer * that.denom + that.numer * this.denom,
this.denom * that.denom
)
像这样重载:
def +(that: Int): Rational =
+(new Rational(that, 1))
我得到以下编译错误:
(fragment of Rational.scala):19: error: value unary_+ is not a member of this.Rational
+(new Rational(that, 1))
^
为什么编译器要寻找 + 方法的一元版本?
【问题讨论】:
标签: scala