Can I use for-comprehenion / yield to create a map in Scala?

aioobe picture aioobe · Nov 18, 2010 · Viewed 13.7k times · Source

Can I "yield" into a Map?

I've tried

val rndTrans = for (s1 <- 0 to nStates;
                    s2 <- 0 to nStates
                        if rnd.nextDouble() < trans_probability)
                            yield (s1 -> s2);

(and with , instead of ->) but I get the error

TestCaseGenerator.scala:42: error: type mismatch;
 found   : Seq.Projection[(Int, Int)]
 required: Map[State,State]
    new LTS(rndTrans, rndLabeling)

I can see why, but I can't see how to solve this :-/

Answer

Vasil Remeniuk picture Vasil Remeniuk · Nov 18, 2010
scala> (for(i <- 0 to 10; j <- 0 to 10) yield (i -> j)) toMap
res1: scala.collection.immutable.Map[Int,Int] = Map((0,10), (5,10), (10,10), (1,10), (6,10), (9,10), (2,10), (7,10), (3,10),  (8,10), (4,10))