Created
July 31, 2016 13:40
-
-
Save HDBandit/4e4ed714e750924d5f666b6c9f4aec20 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Rational { | |
implicit def intToRational(x: Int) = new Rational(x) | |
} | |
class Rational(n: Int, d: Int) { | |
require(d != 0, "Denominator cannot be 0") | |
println("My rational is created") | |
val num = n | |
val denom = d | |
def this(n: Int) = this(n, 1) | |
override def toString = s"$n/$d" | |
def +(that: Rational): Rational = { | |
new Rational( | |
n * that.denom + that.num * d, | |
d * that.denom | |
) | |
} | |
def +(that: Int): Rational = { | |
new Rational( | |
n + that * d, | |
d | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment