Simple composition of functions in Scala

51 Views Asked by At

I have a simplified version of my code. What would be clear, what I want conceptually:

def heavyCalcMul: Int => Int = i => i * 2
def heavyCalcDiv: Int => Int = i => i / 2
def heavyCalcPls: Int => Int = i => i + 2

and I use it like this:

val x = 2
val midResult = heavyCalcMul(x)
val result = heavyCalcDiv(midResult) + heavyCalcPls(midResult)

but I want rewrite this code in this style:

val x = 2
val result = heavyCalcMul(x) { midResult: Int =>
  heavyCalcDiv(midResult) + heavyCalcPls(midResult)
}

is it possible?

1

There are 1 best solutions below

1
On BEST ANSWER

You can use andThen:

val calc = heavyCalcMul
  .andThen(mid => 
     heavyCalcDiv(mid) + heavyCalcPls(mid)
  )

val result2 = calc(x)

Try it out!