vendredi 3 avril 2015

the for-comprehension loops in wrong order with assignment and what is its translation in Scala


Vote count:

0




given val l = List( List(0), List(1) )


The for-loop :



for {
x <- l
_ = println(x)
y <- x
} {println(y)}


//would prints :

List(0)

List(1)

0

1


Is the prints in the order you expected?

And should not it be translated into the following. the translation of for-loop :



l.foreach(
x => {
println(x)
x.foreach(y => println(y))
}
)


List(0)

0

List(1)

1




My Questions:



  1. Why the for-loop is not executed by intuitive order ? (I was expecting the result is of the second example using foreach )

  2. Is my translation wrong ?

  3. Why we must assign something (e.g. _ = print()) in for-condition part? (just a print() will not compile )



asked 2 mins ago







the for-comprehension loops in wrong order with assignment and what is its translation in Scala

Aucun commentaire:

Enregistrer un commentaire