Issue
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] ^
Solution
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
}
Answered By - Levi Ramsey Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.