/**
* 有理数sample; 有理数谓之:2/3,4/6就是我们说的分数
* @param a 分子
* @param b 分母
*/
class Rational(a:Int, b:Int) {
require( b != 0)
override def toString = s"$a / $b"
val n = a
val d = b
def this(n:Int) = this(n, 1)
def add(t:Rational) = if (d == t.d)
new Rational(n + t.n,t.d)
else
new Rational(n * t.d + t.n * d, d * t.d)
def * (t:Rational) = new Rational(n * t.n, d * t.d)
def * (t:Int) = new Rational(n * t, d)
def unary_- = new Rational(-n, -d)
def + (t:Rational) = add(t)
}
object Rational {
implicit def int2Rat(i:Int) = new Rational(i)
}
// 有理数应用测试
val r = new Rational(3, 5) //r: Rational = 3 / 5
-r //res0: Rational = -3 / -5
val rr = new Rational(4) //rr: Rational = 4 / 1
val rrr = rr * r //rrr: Rational = 12 / 5
rr * 4 //res1: Rational = 16 / 1
5 * rr //res2: Rational = 20 / 1
- 操作符就是方法
- 类构造方法更简单
- 字段定义都是不可变的
- 类的对象都是新生成的,而非改变原始对象的状态
- scala的一元操作符让程序更灵活, 譬如上例:-r 中的应用
- implicit 的隐式转换。 implicit是一个强大的功能,也是scala增加java的必备利器。上例中实现了int到rational对象的转换
- class与object。 class就是java中的class, object定义的是一个单例对象