def adder(a:Int,b:Int):Int = {a+b}
def doubler(a:Int):Int = {a*2}
def doubleAdd = doubler _ compose adder
I get the error: type mismatch found: (Int,Int)=>Int required: ? => Int
Then if I just try doubleAdd = doubler(adder _) I get the same error except required Int instead of ? => Int
Is there a way of composing a function with two parameters? Sorry if this is pretty basic, I'm pretty new to the language, and I couldn't find an example with two parameters anywhere.
If we are given two functions, it is possible to create or generate a “new” function by composing one into the other. The step involved is similar when a function is being evaluated for a given value.
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
Function composition is a way in which a function is mixed with other functions. During the composition the one function holds the reference to another function in order to fulfill it's mission.
You're attempting to compose a Function2 (adder) with a Function1, hence the issue. One workaround is to change your definition of Adder to a curried version:
def adder(a: Int)(b: Int):Int = a + b
Then doubleAdd to partially apply adder like this:
def doubleAdd(x: Int) = doubler _ compose adder(x)
What's happening under the hood is transforming adder from a Function2 (Int, Int) => Int
, to a Function1 (Int) => (Int) => Int
, or a function that returns a function. You're then able to compose the function returned from adder with the first parameter already applied.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With