不确定方法在scala类中如何工作
我试图理解《Scala编程-第二版》一书中的add方法。 这是否正确: “add”方法定义了一个Rational类型的操作符。我不知道在新的Rational中发生了什么:不确定方法在scala类中如何工作,scala,Scala,我试图理解《Scala编程-第二版》一书中的add方法。 这是否正确: “add”方法定义了一个Rational类型的操作符。我不知道在新的Rational中发生了什么: numer * that.denom + that.numer * denom, denom * that.denom 此处如何分配数字和名称,为什么每个表达式都用逗号分隔? 全班: class Rational(n: Int , d: Int) { require(d != 0) private val g =
numer * that.denom + that.numer * denom,
denom * that.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)
}
这两个表达式是
Rational
构造函数的参数,因此它们分别是private val
sn
和d
。比如说
class C(a: Int, b: Int)
val c1 = new C(1, 2) // here 1, 2 is like the two expressions you mention
add
方法实现有理数加法:
a c a*d c*b a*d + c*b
--- + --- = ----- + ----- = -----------
b d b*d b*d b*d
在哪里
这两个表达式是
Rational
构造函数的参数,因此它们分别是private val
sn
和d
。比如说
class C(a: Int, b: Int)
val c1 = new C(1, 2) // here 1, 2 is like the two expressions you mention
add
方法实现有理数加法:
a c a*d c*b a*d + c*b
--- + --- = ----- + ----- = -----------
b d b*d b*d b*d
在哪里