简体   繁体   English

在Scala REPL中操作重载

[英]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 . 当然,我期待像2res20: Int = 3 What am I doing wrong? 我究竟做错了什么?

In Scala, all operators are methods. 在Scala中,所有运算符都是方法。 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. 为了覆盖现有方法(因为Int已经定义了一个+方法),唯一的方法是继承和override +方法,然后你需要对派生类型进行操作。

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). 至于重载,在REPL中定义def +方法时你并没有真正重载Int (坦率地说,我很惊讶这个方法在REPL中使用this编译)。 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 : 为了为Int创建一个新的重载,你需要使用pimp我的库模式 ,或者通过隐式类使用 Scala> = 2.10:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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