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! ^^

3
  • 3
    (for (i <- 0 to 10) yield { i.toString->"Number" }).toMap Commented Jul 3, 2018 at 9:54
  • duplicate of stackoverflow.com/questions/4213992/… Commented Jul 3, 2018 at 10:18
  • Oh, my bad, thanks anyway! Commented Jul 3, 2018 at 14:11

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

the keys in the question are String not Int
changed it from: (1 to 10).map( _-> "Number").toMap to (1 to 10).map( _.toString -> "Number").toMap
2

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

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

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.