Scala - how to build an immutable map from a collection of Tuple2s? -


in python, dictionary can constructed iterable collection of tuples:

>>> listoftuples = zip(range(10), [-x x in range(10)]) >>> listoftuples [(0, 0), (1, -1), (2, -2), (3, -3), (4, -4), (5, -5), (6, -6), (7, -7), (8, -8), (9, -9)] >>> thedict = dict(listoftuples) >>> thedict {0: 0, 1: -1, 2: -2, 3: -3, 4: -4, 5: -5, 6: -6, 7: -7, 8: -8, 9: -9} >>>  

is there equivalent scala syntax? see can use varargs type amount of tuple2s construct map, e.g.

scala> val themap = map((0,0),(1,-1)) themap: scala.collection.immutable.map[int,int] = map((0,0), (1,-1))  scala> themap(0) res4: int = 0  scala> themap(1) res5: int = -1  scala> val tuplepairs = list((0,0),(1,-1)) tuplepairs: list[(int, int)] = list((0,0), (1,-1))  scala> val mapfromiterable = map(tuplepairs) <console>:6: error: type mismatch;  found   : list[(int, int)]  required: (?, ?)        val mapfromiterable = map(tuplepairs)                                  ^ 

i loop through , assign each value manually, seems there must better way.

scala> var themap:scala.collection.mutable.map[int,int] = scala.collection.mutable.map()    themap: scala.collection.mutable.map[int,int] = map()  scala> tuplepairs.foreach(x => themap(x._1) = x._2)                                       scala> themap res13: scala.collection.mutable.map[int,int] = map((1,-1), (0,0)) 

using scala 2.8.0 final, can this:

 scala> val tuplepairs = list((0,0),(1,-1)) tuplepairs: list[(int, int)] = list((0,0), (1,-1))  scala> tuplepairs.tomap res0: scala.collection.immutable.map[int,int] = map((0,0), (1,-1)) 

if you're using scala 2.7.7 this, alternative method used:

 scala> val tuplepairs = list((0,0),(1,-1)) tuplepairs: list[(int, int)] = list((0,0), (1,-1))  scala> map(tuplepairs: _*) res2: scala.collection.immutable.map[int,int] = map(0 -> 0, 1 -> -1) 

but can see, in 2.8.0 things have been improved upon.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -