Search code examples
scalaimmutability

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?


Solution

  • 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)