我正在尝试创建一个类以添加有理数
class Rational(val numerator: Int, val denominator: Int) {
require(denominator != 0)
def this(numerator: Int) = this(numerator, 1)
def +(addend: Rational): Rational = {
new EquivalentRationals(this, addend).sum
}
def +(addend: Int): Rational =
new Rational(numerator + (denominator*addend), denominator)
override def toString = numerator + "/" + denominator
}
class EquivalentRationals(a: Rational, b: Rational) {
val first: Rational =
new Rational(a.numerator * b.denominator, a.denominator * b.denominator)
val second: Rational =
new Rational(b.numerator * a.denominator, b.denominator * a.denominator)
def sum(): Rational =
new Rational(first.numerator + second.numerator, second.denominator)
def difference(): Rational =
new Rational(first.numerator - second.numerator, second.denominator)
override def toString = first + " " + second
}
当我尝试从第一类创建对象时出现以下错误
:23: 错误:类型不匹配;找到:Rational(in object $iw)(in object $iw)(in object $iw)(in object $iw) required: Rational(in object $iw)(in object $iw)(in object $iw)(in object $iw)对象 $iw) new EquivalentRationals(this,addend).sum()
我想知道为什么会发生这种情况,并且我也将感谢任何关于添加有理数的替代方法的建议,这些方法也使用单独的类来表示等效分数。(在“scala 编程”一书中,有一个理性的类已经完成了这一点,而无需使用单独的类) 编辑:问题似乎只在 emacs 中使用 scala-mode 时出现。我尝试通过选择“在解释器中加载文件”选项来运行它,所以虽然它通过命令行运行,但我仍然很好奇为什么它不在“inferior-scala”中