13

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

4 Answers 4

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>
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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

Comments

5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.