Overloading Unary Operators in Scala PRO

When overloading an unary operators in Scala we should precede the operator name with ‘unary_’. Not doing so we will get an exception when using it. The following code sample shows that.

package il.ac.hit.samples

object Program
{
  def main(args: Array[String])
  {
    val ob = new RationalNumber(1,3)
    val other = -ob
    println(other)
  }
}

class RationalNumber(a:Int,b:Int)
{
  require (b!=0,"donominator cannot be 0")
  val numerator:Int = a / greatestCommonDivider(a,b)
  val denominator:Int = b / greatestCommonDivider(a,b)
  private def greatestCommonDivider(m:Int,n:Int):Int =
  {
    if(n==0) m else greatestCommonDivider(n,m%n)
  }
  override def toString():String =
  {
    numerator+"/"+denominator
  }
  def unary_- :RationalNumber = new RationalNumber(-numerator,denominator)
}

The following video clip overviews this code sample, shows its execution and explains it.

Share:

banner for the css playlist in hebrew life michael courses for programmers

The First Steps in CSS

Learn CSS using our our videos (in Hebrew) on the CSS (he) playlist on youtube. Do it now. Do it for free.

Good Trainers Collaborate with Others

It is always essential to keep an open mind and learn from others. This applies to everyone, including teachers and especially software development trainers. Software

The Beauty of Code

Coding is Art! Developing Code That Works is Simple. Develop Code with Style is a Challenge!

Update cookies preferences