Reputation: 2661
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
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
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:
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)
}
}
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