我正在尝试为了添加有理数而创建一个类
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(在对象$ iw中)(在对象$ iw中)(在对象$ iw中)(在对象$ iw中) required:Rational(在对象$ iw中)(在对象$ iw中)(在对象$ iw中)(在对象$ iw中) 新的EquivalentRationals(this,addend).sum()
我想知道为什么会发生这种情况,我还要感谢任何有关添加有理数的替代方法的建议,这些方法也使用单独的类来表示等效分数。 (有一个理性的类已经完成了这个,而没有在“scala编程”一书中使用单独的类) 编辑:只有在emacs中使用scala-mode时才会出现问题。我尝试通过选择“在解释器中加载文件”选项来运行它,所以虽然它通过命令行运行但我仍然很好奇为什么它不在“inferior-scala”中