1

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?

3
  • A += (s -> attributeVal) or A updated (s, attributeVal). [source] Commented Feb 13, 2019 at 16:16
  • I tried and see this compilation error : value update is not a member of Map[String,String] [ERROR] A(s)=attributeVal Commented Feb 13, 2019 at 16:19
  • And for A += (s -> attributeVal) I get syntax error Commented Feb 13, 2019 at 16:26

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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
      }
    }
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.