如何编写作为二进制运算符的函数?

时间:2019-04-26 13:35:44

标签: scala operator-overloading

在我的Scala程序中,我有一个数据类型Foo,我想为其编写一个二进制运算符>>

这是一些示例代码。

class Foo {}

object BinaryOps {
  def >>(f1: Foo, f2: Foo): Foo = ???

  def main(args: Array[String]): Unit = {
    val f1 = new Foo()
    val f2 = new Foo()
//  val f3 = f1 >> f2   // Error: cannot resolve symbol >>
    val f4 = >>(f1, f2) // works, but I want the binary op syntax.

//  val f5 = f1 >> f2 >> f3 >> f4   // ultimate goal is to be able to chain calls.
  }
}

到目前为止,我的IDE告诉我它无法解析符号>>,也就是说,编译器没有尝试将其用作二进制运算符。

如何更改它以便找到该符号并将其用作二进制运算符?

编辑:如果无法更改Foo怎么办?如果可以的话怎么办?

1 个答案:

答案 0 :(得分:3)

f1 >> f2的形式实际上表示f1.>>(f2),这意味着Foo应该具有这样的方法。

class Foo {
  def >>(that :Foo) :Foo = ???
  ...

如果无法修改Foo,则可以创建一个隐式转换。

implicit class FooOps(thisfoo :Foo) {
  def >>(thatfoo :Foo) :Foo = ???
}

现在f1 >> f2应该可以工作了。