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)
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.
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.
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.
=> 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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With