Arrays Scala阵列初始化

Arrays Scala阵列初始化,arrays,scala,initialization,Arrays,Scala,Initialization,你有: val array = new Array[Array[Cell]](height, width) 如何将所有元素初始化为新的单元格(“某物”) 谢谢, Etam(Scala新增) Array.fromFunction接受一个函数,该函数接受n个整数参数,并返回这些参数所描述的数组中位置的元素(即f(x,y)应返回数组(x)(y)的元素),然后在单独的参数列表中返回n个描述数组维度的整数。假设已创建数组,您可以使用以下选项: val array = Array.fill(height)

你有:

val array = new Array[Array[Cell]](height, width)
如何将所有元素初始化为新的单元格(“某物”)

谢谢, Etam(Scala新增)


Array.fromFunction接受一个函数,该函数接受n个整数参数,并返回这些参数所描述的数组中位置的元素(即f(x,y)应返回数组(x)(y)的元素),然后在单独的参数列表中返回n个描述数组维度的整数。

假设已创建数组,您可以使用以下选项:

val array = Array.fill(height)(Array.fill(width)(new Cell("something")))
for {
  i <- array.indices
  j <- array(i).indices
} array(i)(j) = new Cell("something")
用于{

i这比fromFunction更好,但它需要scala 2.8。请注意,您可以只使用二维版本的fill:
Array.fill(高度、宽度)(新单元格(“某物”)
Welcome to Scala version 2.8.0.r21376-b20100408020204 (Java HotSpot(TM) Client VM, Java 1.6.0_18).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val (height, width) = (10,20)
height: Int = 10
width: Int = 20

scala> val array = Array.fill(height, width){ new Cell("x") }
array: Array[Array[Cell[java.lang.String]]] = Array(Array(Cell(x), Cell(x), ...
scala>
for {
  i <- array.indices
  j <- array(i).indices
} array(i)(j) = new Cell("something")