用创建一个函数式对象(类Rational)的过程来说明
类Rational是一种表示有理数(Rational number)的类
package com.scala.first /** * Created by common on 17-4-3. */ object Rational { def main(args: Array[String]) { var r1 = new Rational(1, 2) var r2 = new Rational(1) System.out.println(r1.toString) System.out.println(r1.add(r2).toString) var r3 = new Rational(2, 2) System.out.println(r3) System.out.println(r1 + r3) } } class Rational(n: Int, d: Int) { //检查先决条件,不符合先决条件将抛出IllegalArgumentException require(d != 0) //最大公约数 private val g = gcd(n.abs, d.abs) private def gcd(a: Int, b: Int): Int = { if (b == 0) a else gcd(b, a % b) } //进行约分 val numer: Int = n / g val denom: Int = 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 ) } //方法重载 override def toString = numer + "/" + denom //定义方法 def add(that: Rational): Rational = { new Rational( numer * that.denom + that.numer * denom, denom * that.denom ) } //定义方法,自指向this可写可不写 def lessThan(that: Rational): Boolean = { this.numer * that.denom < that.numer * this.denom } }