在Scala中检查foreach中的条件

Dev*_*eer 5 foreach scala

有没有一种方法可以检查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
Run Code Online (Sandbox Code Playgroud)

我知道如何使用普通的for循环和if语句来执行此操作,但是我想使用它,因为我想摆脱Java。

谢谢

oza*_*ata 5

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

例如:

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