Skip to content

Instantly share code, notes, and snippets.

@jakubjanecek
Created April 10, 2013 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakubjanecek/5352686 to your computer and use it in GitHub Desktop.
Save jakubjanecek/5352686 to your computer and use it in GitHub Desktop.
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