Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

anonymous function with multiple parameter lists

Tags:

scala

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.

like image 563
Knows Not Much Avatar asked Feb 06 '23 14:02

Knows Not Much


1 Answers

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
like image 182
jwvh Avatar answered Feb 16 '23 12:02

jwvh