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:

The Visitor Design Pattern

The Visitor Design Pattern

The visitor design pattern allows us to add operations to objects that already exist without modifying their classes and without extending them.

What are Anti Patterns?

Anti Patterns

Unlike design patterns, anti patterns just seem to be a solution. However, they are not a solution and they cause additional costs.

Virtual Threads in Java Professional Seminar

Virtual Threads in Java

The use of virtual threads can assist us with improving the performance of our code. Learn how to use virtual threads effectively.

The Beauty of Code

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

Update cookies preferences