Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Implementation of complex numbers from Czech Scala Enthusiasts coding dojo held on April 9th 2013
class ComplexNumber private (val x: Int, val y: Int) {
def +(c: ComplexNumber) = ComplexNumber(x + c.x, y + c.y)
def *(c: ComplexNumber) = ComplexNumber((x * c.x) - (y * c.y), (y * c.x) + (x * c.y))
// higher-order method
def transform(f: ComplexNumber => ComplexNumber) = f(this)
override def toString = s"$x + ${y}i"
override def equals(obj: Any): Boolean = obj match {
case c: ComplexNumber => x == c.x && y == c.y
case _ => false
}
override def hashCode(): Int = 31 + (31 * x + 31 * y)
}
object ComplexNumber {
val i = ComplexNumber(0, 1)
def apply(x: Int, y: Int) = new ComplexNumber(x, y)
implicit def int2Complex(i: Int) = ComplexNumber(i, 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment