0

I was reading about Maps and so I've tried creating one like this:

val myMap = for(i <- 0 to 10) yield {
  i.toString->"Number"
}

Obviously it would not work. What is the proper way to initialize a map using for loops?

Thanks! ^^

JoeDortman
  • 185
  • 9

2 Answers2

3

Using toMap on some collections with tuple returns scala.collection.immutable.Map where the first value is the key and the second one is the value itself. For the example above you can do the following (and adopt scala style):

(1 to 10).map( _.toString -> "Number").toMap
user3725190
  • 343
  • 4
  • 14
2

You just need to call toMap on the result, like this

val myMap = (for(i <- 0 to 10) yield {
  i.toString -> "Number"
}).toMap
Tim
  • 26,753
  • 2
  • 16
  • 29