1

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

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)
}

可能吗?

4

1 回答 1

6

您可以使用andThen

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

val result2 = calc(x)

试试看!

于 2019-03-21T10:13:28.580 回答