Scala中函数的简单组合

问题描述 投票:1回答: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)
}

可能吗?

scala function-composition scalastyle
1个回答
6
投票

你可以使用andThen

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

val result2 = calc(x)

Try it out!

© www.soinside.com 2019 - 2024. All rights reserved.