0

Why I can't invoke g2 with the second parameter in the line g2(1, _: Int)(9)?

g2(1, _: Int) returns a function <function1> and then I invoke that <function1> with parameter. At the same time in the example above I can invoke f3(9) however it is the same as g2(1, _: Int)(9) IMHO.

// OK

def f1: (Int, Int) => Int   =   _ + _
val f2: (Int, Int) => Int   =   f1
val f3: (Int) => Int        =   f2(1, _: Int)

println {
  f3(9)
}

// FAIL

def g1: (Int, Int) => Int   =   _ + _
val g2: (Int, Int) => Int   =   g1

println {
  g2(1, _: Int)(9) // Error: 'g2' does not take parameters 
}
Finkelson
  • 2,921
  • 4
  • 31
  • 49

2 Answers2

2

It's the issue with the scope of underscore in anonymous functions. See here for the rules: What are the rules to govern underscore to define anonymous function?

According to the rule 1 from the link above g2(1, _: Int)(9) is interpreted as (x: Int) => g2(1, x)(9). So you need to add parentheses, for the rule 2 to start working: (g2(1, _: Int))(9)

Community
  • 1
  • 1
Kolmar
  • 14,086
  • 1
  • 22
  • 25
1

As you add in a comment, (g2(1, _: Int))(9) works.

Scala has multiple parameter lists, so f(x)(y) parses differently from (f(x))(y). As g takes only one parameter list, it can't take the second parameter list, hence the explicit grouping is necessary.

g2(1, _: Int)(9) means: take the function g2(x, y)(z), and apply parameters x = 1, z = 9.

(g2(1, _: Int))(9) means: take the function g2(x, y), and apply parameter x = 1. Then apply y = 9 to the resulting function.

Silly Freak
  • 4,061
  • 1
  • 36
  • 58