这是我的建议。基本上我创建了一系列彼此独立的函数。如果其中一项操作被禁用,我会将其替换为identity
。最后我foldLeft
在该序列上,使用num
参数作为初始值:
case class Config(
addThree: Boolean = true,
halve: Boolean = true,
timesFive: Boolean = true
) {
private val funChain = Seq[Int => Int](
if(addThree) _ + 3 else identity _,
if(halve) _ / 2 else identity _,
if(timesFive) _ * 5 else identity _
)
def doOps(num: Int) = funChain.foldLeft(num){(acc, f) => f(acc)}
}
我放置了doOps()
inside Config
因为它非常适合那里。
Config(true, false, true).doOps(10) //(10 + 3 ) * 5 = 65
如果你是一个受虐狂,foldLeft()
可以这样写:
def doOps(num: Int) = (num /: funChain){(acc, f) => f(acc)}
如果你不喜欢identity
, use Option[Int => Int]
and flatten
:
private val funChain = Seq[Option[Int => Int]](
if(addThree) Some(_ + 3) else None,
if(halve) Some(_ / 2) else None,
if(timesFive) Some(_ * 5) else None
).flatten