Operators like +, – , * and so on are actually not operators in traditional sense in Scala language. They all are methods. :). Scala language provides a relaxed syntax when it comes to method invocations. The dot (.) and braces between the objects and method names are optional. When you say object1 + object2 it actually is translated into object1.+(object2).
Therefore operator overloading in Scala means implementing a method with the operator as the name of the method. Let’s learn this with an example. We’ll create a class called Shape with height and width variables. We’ll implement the + and * methods as shown below.
class Shape(private val theHeight:Int,private val theWidth:Int){ val height = theHeight; val width = theWidth; def +(another:Shape):Shape = { new Shape(this.height+another.height,this.width+another.width) } def *(another:Shape):Shape = { new Shape(this.height*another.height,this.width*another.width) } }
You can invoke the + and * methods on Shape objects as shown below.
var shape1 = new Shape(10,20) var shape2 = new Shape(30,20) var shape3 = shape1 + shape2 println(shape3.height + ", " + shape3.width)//Prints 40,40 var shape4 = shape1 * shape2 println(shape4.height + ", " + shape4.width)//Prints 300,400
You can invoke + and * methods together. You don’t have operator precedence in Scala however. Instead Scala has method priorities. If you invoke multiple methods in a single statement the asterik, slash characters are given high priority followed by the plus, minus and so on. The methods with letters have the least priority. So if you have a method call like this obj1 + obj2 * obj3 foo(obj4). The asterik method is invoked first, followed by plus and finally the foo method is called.
var s1 = new Shape(10,20) var s2 = new Shape(30,40) var s3 = new Shape(50,60) var s4 = s1 + s2 * s3 println(s4.height + ", " + s4.width) //Prints 1510,2420