scala/ScalaBook/chapter-01/light-weight.scala

class Complex(val re: Double, val im: Double) {
    def + (that: Complex) =
      new Complex(re + that.re, im + that.im)
    //def + (that: Double) = 
    //  new Complex(re + 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) = {
      val denom = that.re * that.re + that.im * that.im
      new Complex((re * that.re + im * that.im) / denom,
                  (im * that.re - re * that.im) / denom)
    }
    override def toString =
      if ( re == 0 && im == 0) "0"
      else if ( im == 0 ) re.toString
      else if ( re == 0 ) im + "i"
      else re + (if (im < 0) "" else "+")  + im + "i"     
  }
  implicit def doubleToComplex(x: Double) : Complex  =  new Complex(x, 0.0)
  implicit def intToComplex (x: Int) : Complex = new Complex (x, 0.0)
  //val i = new Complex(0,1);
  object i extends Complex(0, 1)
  var x = i+9.0; var y = -8+i; var z= x*y;
  println("x = " + x + " y = " + y); println(z);