Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are there two sets of arguments/parenthesis in this Scala method definition?

Tags:

syntax

scala

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

like image 446
DJ180 Avatar asked Nov 25 '12 04:11

DJ180


People also ask

What is the syntax of defining method in Scala?

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.

What is an argument in Scala?

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.

What kind of parameters are not needed while calling a method in Scala?

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.


1 Answers

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)

like image 166
DennisVDB Avatar answered Sep 21 '22 16:09

DennisVDB