Different types of brackets in the Scala function definition parameter list

What is the difference between the following two function definitions in Scala:

1) def sum(f: Int => Int)(a: Int, b: Int): Int = { <code removed> }

2) def sum(f: Int => Int, a: Int, b: Int): Int = { <code removed> }

?

The SBT REPL console gives a different meaning to them, so it looks if they are somehow different:

sum: (f: Int => Int, a: Int, b: Int)Int

sum: (f: Int => Int)(a: Int, b: Int)Int

+6
source share
2 answers

The first definition is curried so you can provide a and b at a different time.

For example, if you know the function that you want to use in the current method, but do not yet know the arguments, you can use it like this:

 def mySum(v: Int): Int = v + 1 val newsum = sum(mySum) _ 

At this point, newsum is a function that takes two Int and returns Int .

In the context of summation, this does not seem to make much sense; however, there were many times when I wanted to return different algorithms for parts of the program, based on what I know now, but do not yet know (or do not have access) to the parameters.

Currying buys you this feature.

+4
source

Scala functions support multiple parameter lists to aid in currying. In the first example, you can view the first sum function as one that takes two integers and returns another function (i.e. curry), which can then take the function Int => Int as an argument.

This syntax is also used to create functions that look and behave like new syntax. For example, def withResource(r: Resource)(block: => Unit) can be called:

 withResource(res) { .. .. } 
+2
source

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


All Articles