2

I'm using a tuple within a map to help me assign values in an array, but I'm getting "too many arguments for method update"

val a = Map((1,1) -> "alex", (2,2) -> "Jade")
val boardRep = Array.ofDim[String](3, 3)
a foreach { 
  case (key, value) => {
    boardRep((key._1), (key._2)) = value
  }
}

This should come out to an array with "alex" in the (1,1) spot and "Jade" in the (2,2) spot. What am I doing incorrectly?

3 Answers 3

1

In scala, creating an array of more than 1 dimension means creating Arrays inside Arrays:

scala> val boardRep = Array.ofDim[String](3, 3)
boardRep: Array[Array[String]] = Array(Array(null, null, null), Array(null, null, null), Array(null, null, null))

So to modify the cell (1, 1), you'll have to modify in cell 1 of the main array (boardRep(1): Array(null, null, null)), the cell 1 of this sub-array (boardRep(1)(1))

a foreach {
  case (key, value) =>
    // boardRep((key._1), (key._2)) = value
    boardRep(key._1)(key._2) = value
}

which then gives:

Array(Array(null, null, null), Array(null, alex, null), Array(null, null, Jade))
Sign up to request clarification or add additional context in comments.

Comments

1

You can use arr(key1)(key2) to access into a 2 dimensional array:

@ a foreach {
    case (key, value) => {
      boardRep(key._1)(key._2) = value
    }
  }


@ boardRep
res8: Array[Array[String]] = Array(Array(null, null, null), Array(null, "alex", null), Array(null, null, "Jade"))

Comments

0

Using Array.tabulate it is possible to create an array and populate (some) cells by applying a given function; in this case

Array.tabulate(3,3){ (i, j) => a.getOrElse((i,j), null) }

delivers

Array(Array(null, null, null), Array(null, alex, null), Array(null, null, Jade))

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.