/ totd

TOTD: Scala - Function Composition

Function composition like f(g(x)) and g(f(x)) can be easily achieved in scala using functions with an arity of 1 [e.g. function1].

Suppose we have these two functions:

def double(n: Int) = n * 2
def square(n: Int) = n * n

We can compose them using the compose or the andThen combinators like so:

val squareDouble = double _ compose square _
val doubleSquare = double _ andThen square _

Now you can call either squareDouble or doubleSquare with an Int argument.