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.