The == Operator in Scala PRO

When calling the == operator in Scala we indirectly invoke the equals method. Overriding equals can give a new meaning for the == operator.

The following code sample shows that. The following code snippet is of the Circle class definition, where we override equals.

package il.ac.hit.samples

/**
 * Created by IntelliJ IDEA.
 * User: Haim Michael
 * Date: 12/16/11
 * Time: 10:54 AM
 * To change this template use File | Settings | File Templates.
 */

class Circle(radius:Double)
{
  def area():Double =
  {
    scala.math.Pi*radius*radius
  }
  def this() = this(10)
  override def toString(): String =
  {
    "i m a circle and my area is "+area()
  }
  override def equals(ob:Any): Boolean = 
  {
    ob.isInstanceOf[Circle] && ob.asInstanceOf[Circle].area()==this.area()
  }
}

The following code sample is of the application that uses the Circle class for creating two new objects that represent two circles with the same radius and compare them with each other using the == operator.

package il.ac.hit.samples

/**
 * Created by IntelliJ IDEA.
 * User: user
 * Date: 12/15/11
 * Time: 5:11 PM
 * To change this template use File | Settings | File Templates.
 */

object Demo
{
  def main(args: Array[String])
  {
    val a:Circle = new Circle(4)
    val b:Circle = new Circle(4)
    println(a==b)
  }
}

The following video clip shows an execution of this code sample 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