0
import scala.collection.mutable.Map

var overlapByY: Map[Int, Int] = (0 to records.length).map(a => (a, 0)).toMap

Gives the error

polymorphic expression cannot be instantiated to expected type;
[error]  found   : Map          (in scala.collection.immutable)
[error]  required: Map[Int,Int] (in scala.collection.mutable)
[error]             var overlapByY: Map[Int, Int] = (0 to 8).map(a => (a, 0)).toMap
[error]                                                                       ^

1
  • While all the answers below are correct, the best advice you can get here is do not use mutable collections. Also, do not use var. Commented Aug 20, 2022 at 21:17

2 Answers 2

2

toMap explicitly results in an immutable Map (even though the implementation probably uses a mutable Map internally...)

There are a few ways to go about this. I would tend to use foldLeft:

import scala.collection.mutable

(0 to records.length)  // note that to is inclusive, 0 until records.length might actually be what you want...
  .foldLeft(mutable.Map.empty[Int, Int]) { (map, elem) =>
    map += elem -> 0
  }

This would be equivalent to the even more imperative:

{
  val map = mutable.Map.empty[Int, Int]
  (0 to records.length).foreach { elem => map += elem -> 0 }
  map
}
Sign up to request clarification or add additional context in comments.

Comments

1

toMap returns an immutable.Map so you can't use that if you want a mutable.Map. Use the to method with the mutable.Map object as parameter:

  val overlapByY: mutable.Map[Int, Int] =
    (0 to records.length).map(a => (a, 0)) to mutable.Map

Since it's mutable, you can make overlapByY a val, and still add elements to it:

  overlapByY += ( 1 -> 2)

For older versions of Scala, the old way of doing this was by passing the result of the map as a repeated-parameter using _* to the apply method of the mutable.Map:

  val overlapByY2 =
    mutable.Map((0 to records.length).map(a => (a, 0)): _*)

3 Comments

Hmm, I get the error: ``` type mismatch; [error] found : scala.collection.mutable.Map.type [error] required: scala.collection.generic.CanBuildFrom[Nothing,(Int, Int),?] [error] var overlapByY: mutable.Map[Int, Int] = (0 to records.length).map(a => (a, 0)) to mutable.Map ```
What version of Scala are you using ? This runs fine on Scala 2.13.8. You only need to import the mutable package: import scala.collection.mutable for this, not the whole mutable.Map.
scalaVersion := "2.12.15", Ah right makes sense. Thanks for your help though! Will implement this solution once I update my ver

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.