52

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

DJ180
  • 18,724
  • 21
  • 66
  • 117
  • 11
    http://stackoverflow.com/questions/4915027/two-ways-of-currying-in-scala-whats-the-use-case-for-each/4916606#4916606 –  Nov 25 '12 at 04:37
  • 5
    Hint: hover over the "Scala tag" and click on the ["info" link](http://stackoverflow.com/tags/scala/info). The term here is "Multiple parameter lists". –  Nov 25 '12 at 04:37
  • Possible duplicate of [Two ways of currying in Scala; what's the use-case for each?](http://stackoverflow.com/questions/4915027/two-ways-of-currying-in-scala-whats-the-use-case-for-each) – DJ180 Jan 25 '17 at 15:43

1 Answers1

34

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)

DennisVDB
  • 1,347
  • 1
  • 14
  • 30