I post in this blog entry about the implementation of an immutable complex numbers class in Scala programming language. I have tried in this implementation and as much as possible to use Scala's functional programming style. This post shows how concise and beautiful Scala code could be.
Constructors
We first declare our class. We notice that pass two formal parameters to the class, the real part and the imaginary part of the complex number to be created. Scala creates a default constructor for every class, called the primary constructor. All class parameters will be the primamary constructor formal parameters. Moreover any Scala statements that reside directly in the body of the class, will be added to the body of the primary constructor.
Since every real number is a complex number. It would be nice to be able to create complex numbers from real numbers in an intuitive way. This is achieved by constructor this(real : Double). This is called a secondary constructor. All secondary constructors of a class must call its primary constructor.
* Class Complex
* Implements immutable complex numbers.
* @author Skander Kort (April 2012)
*
* This class maybe freely used and extended in non-commercial and commercial projects
* as long as this copyright comment appears at the head of the class's containing file.
*
*/
class Complex(real : Double, imaginary : Double) {
def re = real
def im = imaginary
def this(real : Double) = this(real, 0)
Pretty Printing
What about having a nice presentation of Complex numbers. This is achieved by overriding function toString(). This function handles the special case separately. In short, in order to be able to convert a complex number to a string. It is enough to be able to compare a complex number to zero (or to any real number) and to be able to convert its real and imaginary parts to strings.
if (this == 0) "0.0" else realPartToString + imaginaryPartToString
def ==(real : Double) : Boolean =
this == new Complex(real)
def ==(that : Complex) =
re == that.re && im == that.im
private def realPartToString() =
if (re == 0) "" else re
private def imaginaryPartToString() =
if (im == 0) "" else (if (im > 0) "+" else "") + im + "*i"
Arithmetic Operators
new Complex(re + that.re, im + that.im)
def -(that : Complex) =
new Complex(re - that.re, im - that.im)
def *(that : Complex) =
new Complex(re * that.re - im * that.im, re * that.im + im * that.re)
def /(that : Complex) : Complex = {
require(that != 0)
(this * that.conj) / (that.abs * that.abs)
}
def conj =
new Complex(re, -im)
def /(that : Double) : Complex = {
require(that != 0)
new Complex(re / that, im / that)
}
def abs =
scala.math.sqrt(re * re + im * im)
def !=(that : Complex) =
!(this == that)