linkhyrule5
linkhyrule5

Reputation: 918

Operating Overloading in the Scala REPL

Probably a very simple answer to this one, but - how do I overload an operator?

The obvious solution seems to be failing, though it's possible I'm misunderstanding what's going wrong:

scala> def +(s:Int): Int = {print (s); this + s}
$plus: (s: Int)Int

scala> 1 + 2
res20: Int = 3

Naturally I was expecting something like 2res20: Int = 3. What am I doing wrong?

Upvotes: 3

Views: 130

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149628

In Scala, all operators are methods. In order to override an existing method (as Int already defines a + method), the only way would be to inherit and override the + method, and then you'd need to operate on the derived type.

As for overloading, you aren't really overloading Int when defining a def + method in the REPL (quite frankly, I'm quite surprised this method compiles with the use of this in the REPL). All you're doing is creating a + method which takes a single argument. In order to create a new overload for Int, you'll need to use the pimp my library pattern, or in Scala >= 2.10 via an implicit class:

scala> implicit class PimpedInt(x: Int) {
     |   def +(i: Int, s: String): Int = {
     |     println(s)
     |     x + i
     |   }
     | }
defined class PimpedInt

scala> 1 + (1, "hello")
hello
res8: Int = 2

Upvotes: 3

Related Questions