Search code examples
scalaoperatorscomparison-operators

Using operator (or synthetic function) as a parameter


Below code works fine

  def exec(f: (Int, Int) => Boolean, p1: Int, p2: Int) = f(p1, p2)
  val >= = (x1: Int, x2: Int) => x1 >= x2
  println(exec(>=, 10, 10))

however the question is, if it's possible to get it working without explicit re-defining operator (synthetic function)?

Update

It's clear that it works absolutely fine like this

println(exec(_ >= _, 10, 10))

The question is whether it's possible to make it working in a form exec(>=, 10, 10) without defining functional value.


Solution

  • Let me try to answer my own question.

    Comparison methods are declared in Int in a following way

    def>=(x: Int): Boolean
    

    So they are called for an instance of Int and applied to one argument. There is no way to pass such methods as parameters without "binding" them with two arguments.

    We can do this by declaring method or functional value in advance and map it to >= method in Int like below

    def >= (x1: Int, x2: Int) = x1 >= x2
    def >= = (_: Int) >= (_: Int)
    val >= = (x1: Int, x2: Int) => x1 >= x2
    val >= = (_: Int) >= (_: Int)
    

    or by using anonymous function in a form _ >= _.