Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an array as the 'value' part of a Map

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.

like image 508
Fred Avatar asked Mar 04 '23 02:03

Fred


1 Answers

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))
like image 120
jwvh Avatar answered Mar 13 '23 07:03

jwvh