views:

699

answers:

4

You have:

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

How do you initialize all elements to new Cell("something")?

Thanks, Etam (new to Scala).

+5  A: 
val array = Array.fromFunction((_,_) => new Cell("something"))(height, width)

Array.fromFunction accepts a function which takes n integer arguments and returns the element for the position in the array described by those arguments (i.e. f(x,y) should return the element for array(x)(y)) and then n integers describing the dimensions of the array in a separate argument list.

sepp2k
+4  A: 
val array = Array.fill(height)(Array.fill(width)(new Cell("something")))
etam
This is nicer than fromFunction, but it requires scala 2.8. Note that you can just use the two-dimensional version of fill: `Array.fill(height, width)(new Cell("something"))`.
sepp2k
+7  A: 
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>
Eastsun
+1  A: 

Assuming the array has already been created, you can use this:

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

If you can initialize at creation, see the other answers.

Daniel