Scala: normal functions versus alternating functions?

What is the difference between the two? I know that their type signatures are different and that all functions start normally and must be .tupled to get their form. What is the advantage of using unprinted (but non-curry) features? Moreover, it seems to me that passing several arguments to the root function automatically unpacks them, so, apparently, they are the same.

The only difference I see is that it forces you to have types for each number of function arguments: Function0 , Function1 , Function2 , Function3 , etc., while interleaved functions are just Function1[A, R] but that seems like a flaw. What is the big advantage of using unrelated functions, which are they by default?

+6
source share
2 answers

Completed functions require that the set object be created when they are called (unless the arguments are packed into a tuple). Functions that are not set-related simply define a method that takes an appropriate number of arguments. Thus, given the architecture of the JVM, non-dial-up functions are more efficient.

+7
source

Consider the following example:

 scala> def mult = (x: Int, y: Int) => x * y mult: (Int, Int) => Int scala> val list = List(1, 2, 3) list: List[Int] = List(1, 2, 3) scala> list zip list map mult <console>:10: error: type mismatch; found : (Int, Int) => Int required: ((Int, Int)) => ? list zip list map mult ^ scala> list zip list map mult.tupled res4: List[Int] = List(1, 4, 9) 

There are many situations when you finish pairing elements in tuples. In such situations, you will need a correction function. But there are many other places where this is not so! For instance:

 scala> list.foldLeft(1)(mult) res5: Int = 6 scala> list.foldLeft(1)(mult.tupled) <console>:10: error: type mismatch; found : ((Int, Int)) => Int required: (Int, Int) => Int list.foldLeft(1)(mult.tupled) ^ 

Thus, in principle, Scala has a dichotomy between tuples and parameters, which means that you need to convert functions from root to undisclosed and vice versa here and there.

+3
source

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


All Articles