Fleshed out the Rational class some more.

This commit is contained in:
Paul Phillips 2011-02-14 15:11:41 -08:00
parent 292533ab06
commit e9b7b4ffab
2 changed files with 22 additions and 0 deletions

View File

@ -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 {
}

View File

@ -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)
}