Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optionally adding items to a Scala Map

I am looking for an idiomatic solution to this problem.

I am building a val Scala (immutable) Map and would like to optionally add one or more items:

val aMap =   Map(key1 -> value1,       key2 -> value2,       (if (condition) (key3 -> value3) else ???)) 

How can this be done without using a var? What should replace the ???? Is it better to use the + operator?

val aMap =   Map(key1 -> value1,       key2 -> value2) +   (if (condition) (key3 -> value3) else ???)) 

One possible solution is:

val aMap =   Map(key1 -> value1,       key2 -> value2,       (if (condition) (key3 -> value3) else (null, null))).filter {         case (k, v) => k != null && v != null       } 

Is this the best way?

like image 620
Ralph Avatar asked May 18 '11 17:05

Ralph


People also ask

How do I add values to a map in Scala?

Add elements to a mutable map by simply assigning them, or with the += method. Remove elements with -= or --= . Update elements by reassigning them.

How do I create a map object in Scala?

Map class explicitly. If you want to use both mutable and immutable Maps in the same, then you can continue to refer to the immutable Map as Map but you can refer to the mutable set as mutable. Map. While defining empty map, the type annotation is necessary as the system needs to assign a concrete type to variable.

What is difference between MAP and HashMap in Scala?

Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. HashMap implements immutable map and uses hash table to implement the same.

Does Scala map preserve order?

Read the part of the answer about the TreeMap using Long keys that reflect when an element was inserted. If your comparator is on the insertion order, the tree will preserve the insertion order.


2 Answers

How about something along the lines of

val optional = if(condition) Seq((key3 -> value3)) else Nil val entities = Seq(key1 -> value1, key2 -> value2) ++ optional val aMap = Map(entities:_*) 
like image 188
sblundy Avatar answered Oct 03 '22 23:10

sblundy


Another possibility is to take advantage of the iterable nature of Option.

A non-empty value o:

scala> val o = Some('z' -> 3) scala> (Seq('x' -> 1, 'y' -> 2) ++ o).toMap res1: scala.collection.immutable.Map[Char,Int] = Map(x -> 1, y -> 2, z -> 3) 

An empty value o:

scala> val o = None scala> (Seq('x' -> 1, 'y' -> 2) ++ o).toMap res2: scala.collection.immutable.Map[Char,Int] = Map(x -> 1, y -> 2) 
like image 42
Eron Wright Avatar answered Oct 04 '22 01:10

Eron Wright