Ivan
Ivan

Reputation: 64227

How to initialize a Scala immutable hashmap with values?

What's the syntax to set immutable hashmap contents on initialization?

For example, if I was willing to hardcode an array, I'd write:

val a = Array (0, 1, 2, 3)

What's the analogue for immutable hashmaps (say I want it to contain 0->1 and 2->3 pairs) (in Scala 2.8)?

Upvotes: 33

Views: 37461

Answers (2)

samthebest
samthebest

Reputation: 31553

To create from a collection (remember NOT to have a new keyword)

val result: HashMap[Int, Int] = HashMap(myCollection: _*)

Upvotes: 5

Arjan Blokzijl
Arjan Blokzijl

Reputation: 6888

Do you mean something like this?


scala> val m = collection.immutable.HashMap(0 -> 1, 2 -> 3)
m: scala.collection.immutable.HashMap[Int,Int] = Map((0,1), (2,3))

scala> m.get(0)
res0: Option[Int] = Some(1)

scala> m.get(2)
res1: Option[Int] = Some(3)

scala> m.get(1)
res2: Option[Int] = None

Upvotes: 56

Related Questions