Why is this partial application not compiling?

Following:

val add = (a: Int, b: Int) => a + b 

converted to:

 object add extends Function2[Int, Int, Int] { def apply(a: Int, b: Int) = a + b } 

a

 val a1 = add(_: Int, 3) 

converted to:

 object a1 extends Function1[Int, Int] { def apply(x: Int): Int = { add(x, 3) } } 

But when I do this:

 scala> val a2 = add _ a2: () => (Int, Int) => Int = <function0> 

And then call a2 , it gives an error message:

 scala> a2(1, 2) <console>:11: error: too many arguments for method apply: ()(Int, Int) => Int in trait Function0 a2(1, 2) ^ 

Why is this? Why is the following done?

 a2()(1, 2) 
+6
source share
1 answer

add already Function2[Int, Int, Int] . If you want a2 have the same type, a simple assignment is enough.

 scala> val a2 = add a2: (Int, Int) => Int = <function2> scala> a2(1, 2) res3: Int = 3 

What you are thinking of is an eta extension of a method into a function. If we had:

 def add(a: Int, b: Int): Int = a + b 

Then we would use add _ to get an eta extension to assign a value.

 scala> def a2 = add _ a2: (Int, Int) => Int scala> a2(1, 2) res4: Int = 3 

But add already a function, so underlining has a different meaning. add now a value, not a method. Since add is a value, it is similar to a method without a parameter that returns Function2[Int, Int, Int] . And if we try to get an eta extension of this, we get () => Function2[Int, Int, Int] .

Consider a simpler example when we have a simple val a = 1 . a is essentially the same as the method with the less parameter, which returns 1 ( def a = 1 ). If I try to get an eta extension, I get () => Int .

 scala> val a = 1 a: Int = 1 scala> val a2 = a _ a2: () => Int = <function0> 
+9
source

Source: https://habr.com/ru/post/987344/


All Articles