Skip to content

Instantly share code, notes, and snippets.

@ajjain
Created December 3, 2013 14:13
Show Gist options
  • Save ajjain/7769807 to your computer and use it in GitHub Desktop.
Save ajjain/7769807 to your computer and use it in GitHub Desktop.
Operator Overloading in Scala
package learn.scala
object OperatorOverloading {
println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet
/**
* We wish to use operators for rational number.
* Example: r1 < r2 instead of using r1.less(r2)
* This can be acheived in scala by understanding below two properties
* a) Infix methods Notation
* r1 less r2 is same as r1.less(r2)
* b) Relaxed identifier
* Scala does support relaxed idenifier names
*/
class Rational(x: Int, y: Int) {
def numer = x;
def denom = y;
/**
* How about unary operators, lets try to expand definition of ++ operator
* Format less definition from:
* def less(r: Rational) = if (this.numer * r.denom < this.denom * r.numer) true else false
*/
def <(r: Rational) = if (this.numer * r.denom < this.denom * r.numer) true else false
/**
* How about ++ operator, lets try to expand definition of ++ operator
*/
def ++ : Rational = {
val numer = this.numer + this.denom
return new Rational(numer, this.denom)
}
/**
* How about prefix unary operators, lets try to expand definition of by prefix unary - operator
*/
def unary_- : Rational = new Rational(-this.numer, this.denom)
override def toString() = this.numer + "/" + this.denom
}
val r1by2 = new Rational(1, 2) //> r1by2 : learn.scala.MethodInfix.Rational = 1/2
val r3by4 = new Rational(3, 4) //> r3by4 : learn.scala.MethodInfix.Rational = 3/4
// below are now valid expression now.
r1by2 < r3by4 //> res0: Boolean = true
-r1by2 //> res1: learn.scala.MethodInfix.Rational = -1/2
r1by2++ //> res2: learn.scala.MethodInfix.Rational = 3/2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment