3

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?

2
  • I guess you are trying to do override here, not overloading as Int has already this operator defined.
    – tkachuko
    Jul 3, 2016 at 13:37
  • What makes you think that the + method you've defined corresponds to the method that gets called in 1 + 2?
    – jub0bs
    Jul 3, 2016 at 13:38

1 Answer 1

3

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
15
  • Why not make PimpedInt extend AnyVal?
    – jub0bs
    Jul 3, 2016 at 13:49
  • 1
    @Jubobs Definitely possible, but wasn't crucial for the example. Jul 3, 2016 at 13:51
  • 1
    @Jubobs I was surprised as well, it seems that this.getClass returns a weird looking type: res1: type = @4d591d15. Not sure what REPL magic is happening behind for this to work. Jul 3, 2016 at 13:55
  • 1
    @VictorMoroz Yes.
    – jub0bs
    Jul 3, 2016 at 14:07
  • 1
    @linkhyrule5 That's not what happens in the REPL or generally when you define a method, sorry to disappoint :). This is what happens to your method. Jul 3, 2016 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.