【发布时间】:2012-09-13 21:49:04
【问题描述】:
我正在尝试理解以下类中的 add 方法,该方法取自“Scala 编程 - 第二版”一书。 它是否正确 : 'add' 采用的方法定义了一个 Rational 类型的运算符。我不知道新 Rational 中发生了什么:
numer * that.denom + that.numer * denom,
denom * that.denom
numer & denom 在这里是如何分配的? , 为什么每个表达式用逗号分隔? 全班:
class Rational(n: Int , d: Int) {
require(d != 0)
private val g = gcd(n.abs, d.abs)
val numer = n / g
val denom = d/ g
def this(n: Int) = this(n, 1)
def add(that: Rational): Rational =
new Rational(
numer * that.denom + that.numer * denom,
denom * that.denom
)
override def toString = numer +"/" + denom
private def gcd(a: Int, b: Int): Int =
if(b == 0) a else gcd(b, a % b)
}
【问题讨论】:
标签: scala