Joe Cheri Ross
Joe Cheri Ross

Reputation: 157

How do I append to a listbuffer which is a value of a mutable map in Scala?

val mymap= collection.mutable.Map.empty[String,Seq[String]]
mymap("key") = collection.mutable.ListBuffer("a","b")
mymap.get("key") += "c"

The last line to append to the list buffer is giving error. How the append can be done ?

Upvotes: 1

Views: 1654

Answers (3)

Ashalynd
Ashalynd

Reputation: 12563

If you really want to have immutable value, then something like this should also work:

val mymap= collection.mutable.Map.empty[String,Seq[String]]
mymap("key") = Vector("a","b")
val oldValue = mymap.get("key").getOrElse(Vector[String]())
mymap("key") = oldValue :+ "c"

I used Vector here, because adding elements to the end of List is unefficient by design.

Upvotes: 0

tommy chheng
tommy chheng

Reputation: 9218

When you run the code in the scala console:

→$scala
scala> val mymap= collection.mutable.Map.empty[String,Seq[String]]
mymap: scala.collection.mutable.Map[String,Seq[String]] = Map()

scala> mymap("key") = collection.mutable.ListBuffer("a","b")

scala> mymap.get("key")
res1: Option[Seq[String]] = Some(ListBuffer(a, b))

You'll see that mymap.get("key") is an optional type. You can't add a string to the optional type.

Additionally, since you typed mymap to Seq[String], Seq[String] does not have a += operator taking in a String.

The following works:

val mymap= collection.mutable.Map.empty[String,collection.mutable.ListBuffer[String]]
mymap("key") = collection.mutable.ListBuffer("a","b")
mymap.get("key").map(_ += "c")

Using the .map function will take advantage of the optional type and prevent noSuchElementException as Łukasz noted.

Upvotes: 2

Sean Vieira
Sean Vieira

Reputation: 159905

To deal with your problems one at a time:

  1. Map.get returns an Option[T] and Option does not provide a += or + method.
  2. Even if you use Map.apply (mymap("key")) the return type of apply will be V (in this case Seq) regardless of what the actual concrete type is (Vector, List, Set, etc.). Seq does not provide a += method, and its + method expects another Seq.

Given that, to get what you want you need to declare the type of the Map to be a mutable type:

import collection.mutable.ListBuffer
val mymap= collection.mutable.Map.empty[String,ListBuffer[String]]
mymap("key") = ListBuffer("a","b")
mymap("key") += "c"

will work as you expect it to.

Upvotes: 0

Related Questions