有没有办法在 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/