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
+
method you've defined corresponds to the method that gets called in1 + 2
?