Operator overloading in Scala and Kotlin: two slightly different ways

Image for post
Image for post
Photo by Crissy Jarvis on Unsplash
        Fraction oneHalf = new Fraction(1, 2);
Fraction oneThird = new Fraction(1, 3);
Fraction sum = oneHalf.plus(oneThird);
Fraction difference = oneHalf.minus(oneThird);
Fraction product = oneHalf.times(oneThird);
// etc.
    val oneHalf = new Fraction(1, 2)
val oneThird = new Fraction(1, 3)
val sum = oneHalf plus oneThird
val difference = oneHalf minus oneThird
val product = oneHalf times oneThird
// etc.
  def +(addend: Fraction): Fraction = {
val crossNumerLeft = this.numerator * addend.denominator
val crossNumerRight = this.denominator * addend.numerator
val crossDenom = this.denominator * addend.denominator
new Fraction(crossNumerLeft + crossNumerRight, crossDenom)
}
  def unary_- = new Fraction(-this.numerator, this.denominator)
  def -(subtrahend: Fraction): Fraction = this + (-subtrahend)
    operator fun plus(addend: Fraction): Fraction {
val crossLeft = this.numerator * addend.denominator
val crossRight = this.denominator * addend.numerator
val crossDenom = this.denominator * addend.denominator
return Fraction(crossLeft + crossRight, crossDenom)
}
    operator fun unaryMinus(): Fraction {
return Fraction(-this.numerator, this.denominator)
}
    operator fun minus(subtrahend: Fraction): Fraction {
return this + (-subtrahend)
}

is a composer and photographer from Detroit, Michigan. He has been working on a Java program to display certain mathematical diagrams.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store