tonglin0325的个人主页

Scala学习笔记——函数式对象

用创建一个函数式对象(类Rational)的过程来说明

类Rational是一种表示有理数(Rational number)的类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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
}


}