scala 标识符案例

package com.youlangta.scalaTest

class Rational(n: Int, d: Int) {
require(d != 0, "分母不能为0")
private val g = gcd(n.abs, d.abs)
val number: Int = n / g
val denom: Int = d / g

override def toString: String = number + "/" + denom

def this(n: Int) = this(n, 1)

def +(that: Rational): Rational = {
new Rational(
number * that.denom + that.number * denom,
denom * that.denom
)
}

def +(i: Int): Rational = {
new Rational(
number + i * denom, denom
)
}


def -(that: Rational): Rational = {
new Rational(
number * that.denom - that.number * denom,
denom * that.denom
)
}

def -(i: Int): Rational = {
new Rational(
number - i * denom, denom
)
}

def *(that: Rational): Rational = {
new Rational(
number * that.number,
denom * that.denom
)
}

def *(i: Int): Rational = {
new Rational(
number * i, denom
)
}

def /(that: Rational): Rational = {
new Rational(
number * that.denom,
denom * that.number
)
}

def /(i: Int): Rational = {
new Rational(
number, denom * i
)
}

private def gcd(a: Int, b: Int): Int = {
if (b == 0) a else gcd(b, a % b)
}
}

  

原文地址:https://www.cnblogs.com/youlangta/p/10207494.html