5

I am trying to declare a simple method in scala with multiple parameter lists.

These two work.

scala> def add(a:Int, b:Int) = a+ b
add: (a: Int, b: Int)Int

scala> def add(a:Int)(b:Int) = a + b
add: (a: Int)(b: Int)Int

This does not...

scala> val add = (a:Int)(b:Int)=>a + b

<console>:1: error: not a legal formal parameter.
Note: Tuples cannot be directly destructured in method or function parameters.
      Either create a single parameter accepting the Tuple1,
      or consider a pattern matching anonymous function: `{ case (param1, param1) => ... }
val add = (a:Int)(b:Int)=>a + b

But why ... all I am trying to do is to assign a anonymous function which takes multiple parameter lists to a value. that works with a single parameter list but not with multiple parameter lists.

1 Answer 1

9

It's just a matter of syntax when declaring the curried arguments.

scala> val add = (a:Int) => (b:Int) => a + b
add: Int => (Int => Int) = <function1>

scala> add(4)
res5: Int => Int = <function1>

scala> res5(9)
res6: Int = 13

Example of anonymous usage:

scala> def doit(f: Int => Int => String): String = f(2)(5)
doit: (f: Int => (Int => String))String

scala> doit(a => b => (a+b).toString)
res8: String = 7
Sign up to request clarification or add additional context in comments.

2 Comments

currying would come later. I want an anonymous function with multiple parameter list. like def foo(x:Int)(y:Int) this works with a def but not when you assign an anonymous function to a val.
Multiple parameter lists is currying. That's just two different ways of describing the same thing. And everything to the right of the = sign, taken as a whole, is an anonymous function. I've added an example of anonymous usage.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.