Leonel
Leonel

Reputation: 29219

How do I write a function as a binary operator?

In my Scala program, I have a data type Foo and I want to write a binary operator >> for it.

Here's some sample code.

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.
  }
}

So far, my IDE shows me that it cannot resolve the symbol >>, that is, the compiler does not attempt to use it as a binary operator.

How can I change it so the symbol is found and can be used as a binary operator?

Edit: what if Foo cannot be changed? what if it can?

Upvotes: 2

Views: 468

Answers (1)

jwvh
jwvh

Reputation: 51271

The form f1 >> f2 actually means f1.>>(f2) which means that Foo should have such a method.

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

If Foo can't be modified you can create an implicit conversion.

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

Now f1 >> f2 should work.

Upvotes: 5

Related Questions