Search code examples
functionscalaargumentschaining

Passing a function to an argument in Scala


Is there any way to do something like argument.<keyword>(function) in Scala?

For example:

[1,2,3].supply(myFunc) yielding 6 if myFunc were the summation function.

It just seems easier to chain functions if I were able to do this, instead of calculating something and 'wrapping it' into an argument for a function call.


Solution

  • You can define it yourself if you want. It's frequently called the "pipe operator":

    class AnyWrapper[A](wrapped: A) {
      def |>[B](f: A => B) = f(wrapped)
    }
    implicit def extendAny[A](wrapped: A): AnyWrapper[A] = new AnyWrapper(wrapped)
    

    Then:

    def plus1(i: Int) = i + 1
    val fortyTwo = 41 |> plus1