2010-04-10 70 views
13

您有:斯卡拉數組初始化

val array = new Array[Array[Cell]](height, width) 

你如何初始化到新小區(「東西」)的所有元素?

謝謝, Etam(斯卡拉新來的)。

回答

16
val array = Array.fill(height)(Array.fill(width)(new Cell("something"))) 
+5

這比fromFunction更好,但它需要scala 2.8。請注意,您可以使用二維版本的填充:'Array.fill(height,width)(new Cell(「something」))''。 – sepp2k 2010-04-10 19:33:58

7
val array = Array.fromFunction((_,_) => new Cell("something"))(height, width) 

Array.fromFunction接受一個函數,它接受N個整參數和返回元件用於通過這些參數(即,F(X,Y所描述的陣列中的位置)應返回該元件陣列(X)( y)),然後是n個整數,用於在單獨的參數列表中描述數組的維數。

19
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> 
5

假設陣列已經創建,您可以使用此:

for { 
    i <- array.indices 
    j <- array(i).indices 
} array(i)(j) = new Cell("something") 

如果你可以在創建初始化,看到其他的答案。