0

I'm pretty new in Scala and trying to change the values in a multi dimension Array in the Scala way if there is such thing :)

Let's see the problem:

val table = Array.fill(5, 5){1}

and I'm trying to change every 1 to 5

for (i <- 0 until table.length) {
  for (j <- 0 until table(i).length) {
    table(i)(j) = 5
  }
}

But I think there will be some other (more functional way) to do the same thing.

Thank you!

1
  • I'm a bit confused why you had to initialize table to have 1s. Commented Mar 18, 2016 at 12:13

1 Answer 1

6
val table = List.fill(5, 5){1}
val all5 = table.map(_.map(_ => 5))
Sign up to request clarification or add additional context in comments.

4 Comments

That produces a copy of the table with all 5s, rather than changing the original. That may or may not be what the OP wanted.
OP said functional, which is easier to reason about when it's immutable.
As I said, may or may not be what he wants. Let's see.
Thank you, it's perfectly fine for me. I think it's nicer to create a new table and don't change the input parameter. Clearly I have to learn more scala because it looks weird for my Java-trained eyes :)

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.