Scala中函数的简单组合

Simple composition of functions in Scala

我有一个简化版的代码。什么会清楚,我在概念上想要什么:

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

我是这样使用它的:

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

但我想用这种风格重写这段代码:

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

可能吗?

您可以使用 andThen:

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

val result2 = calc(x)

Try it out!