Operator Overloading

Technically, Scala has no operators, so operator overloading means overloading symbols like +, +-, and so on. In Scala, these are method names. Operators take advantage of Scala’s lenient method invocation syntax—Scala does not require a dot (.) between the object reference and method name.

These two features combined give the illusion of operator overloading. So, when you call ref1 + ref2, you’re actually writing ref1.+(ref2), and invoking the + method on ref1.

Let’s look at an example of providing the + operator on a Complex class that represents complex numbers. Complex numbers, as we know, have a real part and an imaginary part, and they’re useful in computing complex equations that involve the square root of negative ...

Get Pragmatic Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.