继续上篇
9.方法重载
上面写这这么多,但还不能做混合运算。即不能写成r*2,只能写成r*new Rational(2)
package com.mytest.ch2
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 +(that: Rational): Rational = new Rational(numer * that.denom + that.numer * denom, denom * that.denom)
def +(i: Int): Rational = new Rational(numer + i * denom, denom)
def *(that: Rational): Rational = new Rational(numer * that.numer, denom * that.denom)
def *(i: Int): Rational = new Rational(numer * i, denom)
def -(that: Rational): Rational = new Rational(numer * that.denom - that.numer * denom, denom * that.denom)
def -(i: Int): Rational = new Rational(numer - i * denom, denom)
def /(that: Rational): Rational = new Rational(numer * that.denom, denom * that.numer)
def /(i: Int): Rational = new Rational(numer, denom * i)
override def toString = numer + "/" + denom
private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
}
object Rational {
def main(args: Array[String]) {
val x = new Rational(1, 2)
val y = new Rational(2, 3)
println(x + y)
println(x * y)
println(x - y)
println(x / y)
println(x + 3)
println(x * 3)
println(x - 3)
println(x / 3)
}
}
输出为
7/6
1/3
-1/6
3/4
7/2
3/2
-5/2
1/6
10.隐式转换
上面实现了r+3的形式,但是3+r还是不行。
这里我们可以用隐式转换,把Int转为Rational就行了,这样的话3+r就相当于两个rational相加了
object Rational {
def main(args: Array[String]) {
implicit def intToRational(x: Int) = new Rational(x)
val x = new Rational(1, 2)
println(3 + x)
}
}
这里implicit修饰符告诉编译器,遇到int类型的,直接转为Rational.
11.结束
Scala给与用户大量设计,使用库的能力。自己设计时应该做到简洁,可读,易懂。这里也学到了构造函数,重载等方法。