I am new to Scala and am doing some readings around ScalaSTM.
I would appreciate if someone could simply name the concept below, whereby there are 2 sets of brackets being passed to the method.:
def transfer(amount: Int, a: Ref[Int], b: Ref[Int])(c: Transaction) { a.:=(a.get(c) - amount)(c) b.:=(b.get(c) + amount)(c) }
What concept is being employed within c: Transaction
?
I will read further once I know what I am looking for!
Thanks
Syntax. def functionName ([list of parameters]) : [return type] = { function body return [expr] } Here, return type could be any valid Scala data type and list of parameters will be a list of variables separated by comma and list of parameters and return type are optional.
Scala - Functions with Named Arguments Named arguments allow you to pass arguments to a function in a different order. The syntax is simply that each argument is preceded by a parameter name and an equals sign. Try the following program, it is a simple example to show the functions with named arguments.
A parameterless method is a function that does not take parameters, defined by the absence of any empty parenthesis. Invocation of a paramaterless function should be done without parenthesis. This enables the change of def to val without any change in the client code which is a part of uniform access principle.
This is named Currying
. A curried function is when it has the type A => B => C.
The function def foo(a: A, b: B): C
has the type (A, B) => C
. On the other hand, the function def curriedFoo(a: A)(b: B): C
has the type A => B => C
. With the curried function you could do def curriedFooWithA = curriedFoo(a)
which has the type B => C
. You don't have to provide all the argument in one go.
So, in your case you can provide the amount
, a
, and b
. You'll get a function taking a Transaction
. Another case would be a function of the type Request => DataBase => Int
, where you just provide the Request
, and finally when you really need to run the request, provide the DataBase
to which the request has to be sent.
The type (A, B) => C
and A => B => C
are isomorphic. Scala provides the tupled
and uncurried
that do just that.
def curriedFoo(a: A)(b: B): C = a => b => foo(a, b)
def foo(a: A, b: B): C => (a, b) => curriedFoo(a, b)
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