1

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?

HoTicE
  • 573
  • 2
  • 13

1 Answers1

6

You can use andThen:

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

val result2 = calc(x)

Try it out!

Markus Appel
  • 3,138
  • 1
  • 17
  • 46