PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 20, 2022

[FIXED] How do I populate a Mutable map using a loop in scala?

 September 20, 2022     apache-spark, apache-spark-sql, hashmap, pyspark, scala     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing