From 73df62063a2426d646b335dd42e36068455c77a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Zurcher?= Date: Tue, 9 Apr 2013 22:59:44 +0200 Subject: Scala : add constructor, method less and max to Rationals --- Scala/sandbox/3-rationals.scala | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Scala/sandbox/3-rationals.scala b/Scala/sandbox/3-rationals.scala index 3eec82c..868f216 100644 --- a/Scala/sandbox/3-rationals.scala +++ b/Scala/sandbox/3-rationals.scala @@ -1,7 +1,14 @@ object Rationals { + // primary constuctor class Rational(x :Int, y: Int) { + require(y != 0, "denominator must be non zero") // throws IllegalArgumentException + assert(y != 0) // throws AssertionError + + // another constructor + def this(x: Int) = this(x, 1) + private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) private val g = gcd(x, y) def numer = x / g @@ -9,6 +16,10 @@ object Rationals { def neg = new Rational(-numer, denom) + def less(that: Rational) = this.numer * that.denom < that.numer * this.denom + + def max(that: Rational) = if (this.less(that)) that else this + def add(that: Rational) = new Rational( numer * that.denom + that.numer * denom, @@ -24,6 +35,7 @@ object Rationals { println("Rationals") println(new Rational(2, 3).add(new Rational(3, 4)).toString) println(new Rational(1, 3).sub(new Rational(5 ,7)).sub(new Rational(3, 2)).toString) + println(new Rational(1, 3).max(new Rational(5 ,7)).toString) } } -- cgit v1.1-2-g2b99