Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I yield an immutable.Map in Scala?

I have tried this but it does not work:

val map:Map[String,String] = for {
    tuple2 <- someList
  } yield tuple2._1 -> tuple2._2

How else would I convert a List of Tuple2s into a Map?

like image 907
Jasper Avatar asked May 04 '10 07:05

Jasper


People also ask

Is map immutable in Scala?

By default, Scala uses the immutable Map. If you want to use the mutable Map, you'll have to import scala. collection. mutable.

How can we convert mutable map to immutable Scala?

If you just want a mutable HashMap , you can just use x. toMap in 2.8 or collection. immutable. Map(x.

How do I append a map in Scala?

The concatenation of Scala map is obtained by utilizing ++ operator. Return Type: It returns a single map by concatenating two maps but it separates the identical keys. As we can see in above example, we joined two maps by using ++ operator.

How do I create a map in Scala?

A Map is an Iterable consisting of pairs of keys and values (also named mappings or associations). Scala's Predef object offers an implicit conversion that lets you write key -> value as an alternate syntax for the pair (key, value) .


1 Answers

It couldn't be simpler:

Map(listOf2Tuples: _*)

using the apply method in Map companion object.

like image 171
Alexey Romanov Avatar answered Oct 16 '22 10:10

Alexey Romanov