Suppose I have two functions f
and g
:
val f: (Int, Int) => Int = _ + _
val g: Int => String = _ + ""
Now I would like to compose them with andThen
to get a function h
val h: (Int, Int) => String = f andThen g
Unfortunately it doesn't compile :(
scala> val h = (f andThen g)
<console> error: value andThen is not a member of (Int, Int) => Int
val h = (f andThen g)
Why doesn't it compile and how can I compose f
and g
to get (Int, Int) => String
?
Val functions inherit the andThen function and we will show how to use the andThen function to compose two functions together. Mathematically speaking, (f andThen g)(x) = g(f(x)). The results of the first function f(x) is ran first and will be passed as input to the second function g(x).
=> 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 .
Scala - Functions with Named Arguments Named arguments allow you to pass arguments to a function in a different order. The syntax is simply that each argument is preceded by a parameter name and an equals sign. Try the following program, it is a simple example to show the functions with named arguments.
Currying is the process of converting a function with multiple arguments into a sequence of functions that take one argument. Each function returns another function that consumes the following argument.
It doesn't compile because andThen
is a method of Function1
(a function of one parameter: see the scaladoc).
Your function f
has two parameters, so would be an instance of Function2
(see the scaladoc).
To get it to compile, you need to transform f
into a function of one parameter, by tupling:
scala> val h = f.tupled andThen g
h: (Int, Int) => String = <function1>
test:
scala> val t = (1,1)
scala> h(t)
res1: String = 2
You can also write the call to h
more simply because of auto-tupling, without explicitly creating a tuple (although auto-tupling is a little controversial due to its potential for confusion and loss of type-safety):
scala> h(1,1)
res1: String = 2
Function2
does not have an andThen
method.
You can manually compose them, though:
val h: (Int, Int) => String = { (x, y) => g(f(x,y)) }
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