5

The first part of the code below successfully stores a tuple in the value part of a Map. The second part is my attempt to store an array instead of a tuple. It does not work. What is wrong?

object MyClass {

  def main(args: Array[String]) {
    val m1 = Map("fname" -> (1,2), "lname" -> (3,4))
    for ((k,v) <- m1) printf("key: %s, value: %s, 0: %s\n", k, v, v._1)

    var states = scala.collection.mutable.Map[String, new Array[Int](3)]()
    val states += ("fname" -> (1,2,3))
    val states += ("lname" -> (4,5,6))
    for ((k,v) <- states) printf("key: %s, value: %s, 0: %s\n", k, v, v._1)         
  }
}

Here are the errors I get.

Here are the errors I get

Once I understand the syntax to do the job, I also want to access individual elements in the array.

1
  • Please do not include images of text. They are difficult to read, and they are impossible for the visually impaired to read. They also can't be indexed or searched. Instead, copy and paste the text directly into the post. Commented Dec 14, 2019 at 15:57

1 Answer 1

7

Array[Int] is a type. new Array[Int](3) is a value. When declaring a Map you need types, not values: Map[String,Array[Int]]

(1,2,3) is a tuple (or 3-tuple) but you want an array: Array(1,2,3)

v._1 is the first element of a tuple but you want the first element of an array: v(0) or v.head

This compiles.

var states = scala.collection.mutable.Map[String,Array[Int]]()
states += ("fname" -> Array(1,2,3))
states += ("lname" -> Array(4,5,6))
for ((k,v) <- states) printf("key: %s, value: %s, 0: %s\n", k, v, v(0))
Sign up to request clarification or add additional context in comments.

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.