Scala Map from tuple iterable

Use TraversableOnce.toMap which is defined if the elements of a Traversable/Iterable are of type Tuple2. (API)

val map = foo.map(x=>(x, f(x)).toMap

val map = foo zip (foo map f) toMap

Alternatively you can use use collection.breakOut as the implicit CanBuildFrom argument to the map call; this will pick a result builder based on the expected type.

scala> val x: Map[Int, String] = (1 to 5).map(x => (x, "-" * x))(collection.breakOut)
x: Map[Int,String] = Map(5 -> -----, 1 -> -, 2 -> --, 3 -> ---, 4 -> ----)

It will perform better than the .toMap version, as it only iterates the collection once.

It's not so obvious, but this also works with a for-comprehension.

scala> val x: Map[Int, String] = (for (i <- (1 to 5)) yield (i, "-" * i))(collection.breakOut)
x: Map[Int,String] = Map(5 -> -----, 1 -> -, 2 -> --, 3 -> ---, 4 -> ----)