From e9b7b4ffab333fcbc699be1f92a800ecddd1bc29 Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Mon, 14 Feb 2011 15:11:41 -0800 Subject: [PATCH] Fleshed out the Rational class some more. --- src/main/{ => scala}/example/Rational.scala | 16 ++++++++++++++++ src/main/scala/example/package.scala | 6 ++++++ 2 files changed, 22 insertions(+) rename src/main/{ => scala}/example/Rational.scala (61%) create mode 100644 src/main/scala/example/package.scala diff --git a/src/main/example/Rational.scala b/src/main/scala/example/Rational.scala similarity index 61% rename from src/main/example/Rational.scala rename to src/main/scala/example/Rational.scala index 72e27535b..a0e626c21 100644 --- a/src/main/example/Rational.scala +++ b/src/main/scala/example/Rational.scala @@ -17,6 +17,18 @@ class Rational(n: Int, d: Int) { val numerator = n / g val denominator = d / g + // Assume we have r1: Rational, r2: Rational, and num: Int. + // Since + is a method like any other, if we define it with a + // Rational argument then r1 + r2 is defined. + def +(that: Rational): Rational = new Rational( + this.numerator * that.denominator + that.numerator * this.denominator, + this.denominator * that.denominator + ) + // You can overload the + method with an Int argument: now r1 + num + // is also defined. However to make num + r1 work similarly requires + // an implicit conversion. (See the example package object.) + def +(that: Int): Rational = this + new Rational(that) + // toString overrides a method in AnyRef so "override" is required. override def toString = n + "/" + d + ( // The result of the if/else is a String: @@ -24,3 +36,7 @@ class Rational(n: Int, d: Int) { else " (" + numerator + "/" + denominator + ")" // the reduced form otherwise ) } + +// The Rational companion object. +object Rational { +} \ No newline at end of file diff --git a/src/main/scala/example/package.scala b/src/main/scala/example/package.scala new file mode 100644 index 000000000..09ad32615 --- /dev/null +++ b/src/main/scala/example/package.scala @@ -0,0 +1,6 @@ +// The example package object. +package object example { + // Importing an implicit method of type Int => Rational will + // henceforth let us use Ints as if they were Rationals. + implicit def intToRational(num: Int): Rational = new Rational(num) +} \ No newline at end of file