scalafunction-compositionscalastyle

Simple composition of functions in Scala


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?


Solution

  • You can use andThen:

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

    Try it out!