Operator overloading

Like C++, Scala permits operator overload. This feature is great for creating custom Domain Specific Languages (DSL), which can be useful to create better software abstractions or even internal or external APIs for developers, or for business people. You should use this feature with wisdom — imagine if all frameworks decide to overload the same operators with implicits! You might run into trouble. Scala is a very flexible language compared to Java. However, you need to be careful, otherwise you could create code that's hard to maintain or even incompatible with other Scala applications, libraries, or functions.

Scala operator overloading in Scala REPL

Following is an example using Scala operator overloading in Scala REPL:

$ scala

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).

Type in expressions for evaluation. Or try :help. scala>case class MyNumber(value:Int){

| def +(that:MyNumber):MyNumber = new MyNumber(that.value + this.value)

| def +(that:Int):MyNumber = new MyNumber(that + this.value)

| }

defined class MyNumber scala>val v = new MyNumber(5) v: MyNumber = MyNumber(5) scala>



scala>println(v + v)


scala>println(v + new MyNumber(4))


scala>println(v + 8)



As you can see, we have two functions called +. One of this functions receives a MyNumber case class, and the other receives a Int value. You can use OO in Scala with regular classes and functions as well if you wish. We're also favoring immutability here because we always create a new instance of MyNumber when the operation + happens.

< Prev   CONTENTS   Source   Next >