As in C++, Scala supports operator overloading:
class Rational(num: Int = 0, den: Int = 1) {
if (den <= 0)
throw new IllegalArgumentException("denominator
must be > 0")
val d = MathUtils.gcd(num, den)
val numerator = num / d
val denominator = den / d
def *(other: Rational) = new Rational(numerator
* other.numerator, denominator * other.denominator)
def +(other: Rational) =
new Rational(numerator * other.denominator
+ denominator * other.numerator, denominator * other.denominator)
// etc.
override def toString: String = {
if (numerator == 0) "0"
else if (denominator == 1) numerator.toString
else numerator.toString + "/"
+ denominator.toString
}
}
Notes:
· Since the parameters num and den are not used in any method, they are not fields. Instead, we can use their reduced values to initialize numerator and denominator.
· toString is inherited from the Any class and is called in all contexts where objects need to be converted to string representations. We override it to produce fractional or integral notations.
· My MathUtils.gcd is defined elsewhere and uses Euclid's algorithm. Look it up.
· Add – and / to the Rational class declaration
· Create a Complex class.
Here's a tester singleton:
object Main extends App {
try {
val
rat1 = new Rational(6, 8)
val
rat2 = new Rational(2)
val
rat3 = new Rational()
val
rat4 = new Rational(10, 14)
val
rat5 = rat1 + rat4
val
rat6 = rat1 * rat4
println(rat1)
println(rat2)
println(rat3)
println(rat4)
println(rat5)
println(rat6)
val
rat7 = new Rational(3, -4)
} catch {
case
e: IllegalArgumentException => println("math error: " + e.toString)
case
_: Throwable => println("weird error")
}
}
And here's the output it produces:
3/4
2
0
5/7
41/28
15/28
math error: java.lang.IllegalArgumentException:
denominator must be > 0