VictorGram
VictorGram

Reputation: 2661

Scala map : How to add new entries

I have created my scala map as :

val A:Map[String, String] = Map()

Then I am trying to add entries as :

val B = AttributeCodes.map { s =>

    val attributeVal:String = <someString>
    if (!attributeVal.isEmpty)
    {
      A + (s -> attributeVal)
    }
    else
      ()
  }

And after this part of the code, I am seeing A is still empty. And, B is of type :

Pattern: B: IndexedSeq[Any]

I need a map to add entries and the same or different map in return to be used later in the code. However, I can not use "var" for that. Any insight on this problem and how to resolve this?

Upvotes: 1

Views: 4145

Answers (2)

Ivan Stanislavciuc
Ivan Stanislavciuc

Reputation: 7275

Scala uses immutability in many cases and encourages you to do the same.

Do not create an empty map, create a Map[String, String] with .map and .filter

val A = AttributeCodes.map { s =>
      val attributeVal:String = <someString>
      s -> attributeVal
}.toMap.filter(e => !e._1.isEmpty && !e._2.isEmpty)

Upvotes: 4

user31601
user31601

Reputation: 2610

In Scala, the default Map type is immutable. <Map> + <Tuple> creates a new map instance with the additional entry added.

There are 2 ways round this:

  1. Use scala.collection.mutable.Map instead:

    val A:immutable.Map[String, String] = immutable.Map()
    
    AttributeCodes.forEach { s =>
      val attributeVal:String = <someString>
      if (!attributeVal.isEmpty){
        A.put(s, attributeVal)
      }
    }
    
  2. Create in immutable map using a fold:

    val A: Map[String,String] = AttributeCodes.foldLeft(Map(), { m, s =>
      val attributeVal:String = <someString>
      if (!attributeVal.isEmpty){
        m + (s -> attributeVal)
      } else {
        m
      }
    }
    

Upvotes: 1

Related Questions