Scala, a two-value constituent function

def adder(a:Int,b:Int):Int = {a+b} def doubler(a:Int):Int = {a*2} def doubleAdd = doubler _ compose adder 

I get an error: type mismatch found: (Int, Int) => Int required :? => Int

Then, if I just try doubleAdd = doubler (adder _), I get the same error except the required Int instead? => Int

Is there a way to create a function with two parameters? Sorry if this is pretty simple, I'm pretty new to this language, and I could not find an example with two parameters anywhere.

+7
scala
source share
1 answer

You are trying to create Function2 (adder) using Function1, hence the problem. One way is to change the definition of Adder to a version with a map:

 def adder(a: Int)(b: Int):Int = a + b 

Then doubleAdd to partially apply the adder as follows:

 def doubleAdd(x: Int) = doubler _ compose adder(x) 

What happens under the hood converts the adder from Function2 (Int, Int) => Int to Function1 (Int) => (Int) => Int or a function that returns a function. Then you can compose the function returned from the adder, with the first parameter already applied.

+6
source share

All Articles