我目前有一个Java程序,它执行以下操作:
int nvars = 10;
long vars[] = new long[nvars];
for(int i = 0; i < nvars; i++) {
vars[i] = someFunction(i);
anotherFunction(vars[i]);
}
我将其转换为Scala代码,并具有:
val nvars: Int = 10
val vars: Array[Long] = new Array[Long](nvars)
for ( i <- 0 to nvars-1 )
vars(i) = someFunction(i)
anotherFunction(vars(i))
}
关于如何使此(更多)功能起作用的任何建议?
最佳答案
Array随播对象中有许多有用的构造方法,例如,根据您的情况,可以使用tabulate
:
val nvars: Int = 10
val vars = Array.tabulate(nvars){ someFunction } // calls someFunction on the values 0 to nvars-1, and uses this to construct the array
vars foreach (anotherFunction) // calls anotherFunction on each entry in the array
如果
anotherFunction
返回结果,而不仅仅是一个“副作用”函数,则可以通过调用map
捕获该结果:val vars2 = vars map (anotherFunction) // vars2 is a new array with the results computed from applying anotherFunction to each element of vars, which is left unchanged.