Etam
Etam

Reputation: 4673

Scala array initialization

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).

Upvotes: 13

Views: 15083

Answers (4)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297155

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.

Upvotes: 5

Eastsun
Eastsun

Reputation: 18859

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>

Upvotes: 19

Etam
Etam

Reputation: 4673

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

Upvotes: 16

sepp2k
sepp2k

Reputation: 370092

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.

Upvotes: 7

Related Questions