scala - 在 Scala 中检查 foreach 中的条件

标签 scala foreach

有没有办法在 Scala 的 foreach 循环中检查条件。这个例子是我想遍历一个整数数组并对正数做一些任意的数学运算。

val arr = Array(-1,2,3,0,-7,4) //The array

//What I want to do but doesn't work

arr.foreach{if(/*This condition is true*/)
              {/*Do some math and print the answer*/}}

//Expected answer for division by six is 0.333333333 \n 0.5 \n 0.666666667
//Which is 2/6, 3/6 and 4/6 respectively as they appear in the array

我知道如何使用普通的 for 循环和 if 语句来做到这一点,但我想使用它,因为我想摆脱 java。

谢谢

最佳答案

foreach函数将列表/数组中的每一项都带入,您应该在使用之前将其设置为变量。

例如:

arr.foreach( variable_name => {
    if(/*This condition is true*/){
        /*Do some math and print the answer*/
    }
})

关于scala - 在 Scala 中检查 foreach 中的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45297940/

相关文章:

scala - StatusDescription=此请求无权使用此权限执行此操作

scala - 如何在运行时编译/评估 Scala 表达式?

scala - Applicative vs. monadic 组合器和 Scalaz 中的自由 monad

php foreach 每 100 次 sleep 然后继续

kotlin - 从 forEach kotlin 返回单个值

scala - Spark:DataFrame如何在groupBy结果上使用Sum

scala - sbt:如何运行集成测试

php - 为什么这个 foreach 循环提前结束?

jquery - 我在 JQuery 中的重命名功能在 Foreach 语句中不起作用?

php - 运行第二个循环时取消设置数据