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. Commented 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? Commented 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 
Sign up to request clarification or add additional context in comments.

15 Comments

Why not make PimpedInt extend AnyVal?
@Jubobs Definitely possible, but wasn't crucial for the example.
@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.
@VictorMoroz Yes.
@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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.