用高阶方法替换 if

Replacement of if with higher order method

最不推荐在 scala 中使用 if 块进行分布式计算。我有代码,我想用 Scala 高阶方法替换 if 。我怎样才能做到这一点。 给出了详细代码Here

包含 if 块的部分代码。

var bat = DenseVector.fill(N)(new BAT12(d , MinVal , MaxVal ))
bat.foreach{x => x.BestPosition = x.position;x.fitness =  Sphere(x.position)  ; x.BestFitness = x.fitness}
bat.foreach(x =>
if(x.BestFitness < GlobalBest_Fitness)
{
 GlobalBest_Fitness =x.BestFitness ;GlobalBest_Position = x.BestPosition
})

尝试

bat.filter(_.BestFitness < GlobalBest_Fitness).foreach { x =>
  GlobalBest_Fitness = x.BestFitness
  GlobalBest_Position = x.BestPosition
}

在foreach之前做一个过滤,以if条件为过滤条件。然后做无条件的foreach。