Muhammad Hewedy
Muhammad Hewedy

Reputation: 30058

Calling a curried method in Scala

When I define a curried function like:

def fx(x: Int) (f: Int => Int): Int = f(x)

I can call it using:

fx(2)(x => x * x)

But cannot call it using:

(fx 2) (x => x * x)

However

If we take the foldLeft fun from scala std library, with signature:

def foldLeft[B](z: B)(f: (B, A) => B): B

I can call it using:

(xs foldLeft 0 ) ( _ + _)

But cannot call it using:

xs foldLeft (0) ( _ + _)

Question:

Why in case if my defined fun, I can call it using f(x)(fx), but cannot call it using (f x)(fx), However in case of foldleft, I can call it using (obj f x)(fx) but cannot call it using obj f (x) (fx) ?

Hint: I know this is because operator precedence, but need detailed answer

Upvotes: 0

Views: 134

Answers (1)

Sascha Kolberg
Sascha Kolberg

Reputation: 7152

In your example you are not using fx in infix position. A function or operator in infix requires an instance where this function is called on left of the function or operator and an argument to the right.

Example:

(xs foldLeft 0 ) ( _ + _)

foldLeft(infix) is called on xs (left) - which is some Collection - passing 0(right) as argument.

In your example:

(fx 2) (x => x * x)

The object fx is called on is missing. If you change your example a bit, it works:

object someInstance {
  def fx(x: Int)(f: Int => Int): Int = f(x)

  val test = (this fx 2) (x => x * x)
}

// OR
val test2 = (someInstance fx 2) (x => x * x)

It would work.

Upvotes: 2

Related Questions