# Scala 类和对象 (五)

2018-09-28 18:16 更新

## 定义运算符

``````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
override def toString = numer + "/" +denom
def +(that:Rational)  =
new Rational(
numer * that.denom + that.numer* denom,
denom * that.denom
)
def * (that:Rational) =
new Rational( numer * that.numer, denom * that.denom)
def this(n:Int) = this(n,1)
private def gcd(a:Int,b:Int):Int =
if(b==0) a else gcd(b, a % b)
}``````

``````scala> val x= new Rational(1,2)
x: Rational = 1/2
scala> val y=new Rational(2,3)
y: Rational = 2/3
scala> x+y
res0: Rational = 7/6
scala> x+ x*y
res1: Rational = 5/6``````

## Scala中的标识符

Scala 的命名规则采用和 Java 类似的 camel 命名规则，首字符小写，比如 toString。类名的首字符还是使用大写。此外也应该避免使用以下划线结尾的标志符以避免冲突。符号标志符包含一个或多个符号，如+，:，? 等，比如:

+ ++ ::: < ?> :->

Scala 内部实现时会使用转义的标志符，比如:-> 使用 \$colon\$minus\$greater 来表示这个符号。因此如果你需要在 Java 代码中访问:->方法，你需要使用 Scala 的内部名称 \$colon\$minus\$greater。

## 方法重载

``````def + (i:Int) =
new Rational (numer + i * denom, denom)``````

## 隐式类型转换

``````scala> val x =new Rational(2,3)
x: Rational = 2/3``````
``````scala> val y = new Rational(3,7)
y: Rational = 3/7``````
``````scala> val z = 4
z: Int = 4``````
``````scala> x + z
res0: Rational = 14/3``````
``````scala> x + 3
res1: Rational = 11/3``````
``````scala> 3 + x
<console>:10: error: overloaded method value + with alternatives:
(x: Double)Double <and>
(x: Float)Float <and>
(x: Long)Long <and>
(x: Int)Int <and>
(x: Char)Int <and>
(x: Short)Int <and>
(x: Byte)Int <and>
(x: String)String
cannot be applied to (Rational)
3 + x
^``````

``implicit def intToRational(x:Int) = new Rational(x)``

``````scala> val r = new Rational(2,3)
r: Rational = 2/3
scala> r + 2
res0: Rational = 8/3
scala> 2 + r
res1: Rational = 8/3``````

App下载