Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial application of curried constructors in Scala

Tags:

scala

currying

Consider the following:

class A(foo: Int)(bar: Int)(baz: Int)
object A{
    def apply(foo: Int)(bar: Int)(baz: Int) = new A(foo)(bar)(baz)
}

With the apply method I can do the following:

scala> A(1)(2)(3)
res12: Script.A = Script$A@7a6229e9

scala> A(1)_
res13: Int => (Int => Script.A) = <function1>

Why is it that I can't do the following:

scala> new A(1)_
<console>:21: error: missing arguments for constructor A in class A
              new A(1)_
              ^

Am I missing something syntax wise? I thought constructors are meant to be just methods on the class, so they should be lifted to functions when needed (much like the apply method above)

like image 780
Henry Henrinson Avatar asked Jun 26 '14 09:06

Henry Henrinson


People also ask

What is Partially applied functions in Scala?

The Partially applied functions are the functions which are not applied on all the arguments defined by the stated function i.e, while invoking a function, we can supply some of the arguments and the left arguments are supplied when required.

What is the use of currying functions in Scala?

Currying in Scala is simply a technique or a process of transforming a function. This function takes multiple arguments into a function that takes single argument. It is applied widely in multiple functional languages.

What is currying in spark?

Currying is the process of converting a function with multiple arguments into a sequence of functions that take one argument. Each function returns another function that consumes the following argument.

What does => mean in Scala?

=> is the "function arrow". It is used both in function type signatures as well as anonymous function terms. () => Unit is a shorthand for Function0[Unit] , which is the type of functions which take no arguments and return nothing useful (like void in other languages).


1 Answers

Calling new on the class supposed to create an instance of that class (A in you case), but what you are trying to do with new A(1) _ is to make an instance of A class without complete data for the contractor, which is essentially not logical at all. But writing A(1) _ is correct and logical cause in this case you are lifting a method into a function (apply method from A companion object) which already has all the data to make an instance of that class.

like image 115
4lex1v Avatar answered Oct 08 '22 13:10

4lex1v