Does Scala support Operator Overloading?
In object-oriented programming, operator overloading—less commonly known as operator ad hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading is generally defined by the language, the programmer, or both.Below is an example which elaborates on how is this supported. I am extending binary <, unary pre negation (-) and unary post ++ operator for a custom datatype Rational.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
No comments:
Post a Comment