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.
Once I understand the syntax to do the job, I also want to access individual elements in the array.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With