简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM