给定以下代码:
case class Config(
addThree: Boolean = true,
halve: Boolean = true,
timesFive: Boolean = true
)
def doOps(num: Integer, config: Config): Integer = {
var result: Integer = num
if ( config.addThree ) {
result += 3
}
if ( config.halve ) {
result /= 2
}
if ( config.timesFive ) {
result *= 5
}
result
}
val config = Config(true,false,true)
println( doOps(20, config) )
println( doOps(10, config) )
我想用更有效和惯用的构造替换丑陋的 doOps 方法。具体来说,我想构建一个函数链,仅根据所使用的特定配置执行所需的转换。我知道我可能想创建某种部分应用的函数,我可以将 Integer 传递到其中,但我对如何以有效的方式实现这一点持空白。
我特别想避免 doOps 中的 if 语句,我希望得到的结构只是一个函数链,它调用链中的下一个函数而不首先检查条件。
生成的代码,我想看起来像这样:
case class Config(
addThree: Boolean = true,
halve: Boolean = true,
timesFive: Boolean = true
)
def buildDoOps(config: Config) = ???
val config = Config(true,false,true)
def doOps1 = buildDoOps(config)
println( doOps1(20) )
println( doOps1(10) )