blunderboy blunderboy - 1 year ago 95
Scala Question

How to instantiate a collection.mutable.Map[String, Any] in scala?

I want to build a map ieratively So I have taken a mutable map. I want to initialize this with empty values.

I have tried this

val resultingMap: collection.mutable.Map[String, Any] = _

But it assigns
to resultingMap and hence when I try to add a record to it, It rightfully throws an exception.

So I tried a hacky way like this

val resultingMap: collection.mutable.Map[String, Any] = collection.mutable.Map("" -> "")

It works but I would like to use a better + standard approach of doing this.

Answer Source

Map.empty[A, B] create creates an empty Map with no key value pairs in it.

import scala.collection.mutable._

val resultingMap: Map[String, Any] = Map.empty[String, Any]

Scala REPL

scala> import scala.collection.mutable._
import scala.collection.mutable._

scala> Map.empty[String, Any]
res29: Map[String, Any] = Map()

scala> val map = Map.empty[String, Any]
map: Map[String, Any] = Map()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download