Kevin Li
Kevin Li

Reputation: 1538

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.

Upvotes: 0

Views: 1074

Answers (2)

Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 60006

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

Upvotes: 3

Jesper
Jesper

Reputation: 206996

Do you mean something like this:

val sum = { (a: Int, b: Int) => a + b }

List(1, 2, 3).reduceLeft(sum)

Upvotes: 0

Related Questions