- for {i <- generator
- if guard
- j = assignment } yield result
The generator, guard, assignment and result are all expressions which means they can all be blocks or simple statements. Most commonly you will see them as simple statements:
- scala> for {i <- 1 to 10
- | if i % 2 == 0
- | j = i } yield j
- res50: scala.collection.immutable.IndexedSeq[Int] = IndexedSeq(2, 4, 6, 8, 10)
But since they are expressions they can be more complex:
- scala> for {
- | i <- {
- | val start = nextInt(3)
- | val end = nextInt(10)+start
- | start to end
- | }
- | if {
- | val cut = nextInt(3)+1
- | i % cut == 0
- | }
- | j = {
- | val x = i+1
- | x / 2
- | }
- | } yield {
- | // do a debug println
- | println(j)
- | j
- | }
- 1
- 1
- 2
- 3
- res53: scala.collection.immutable.IndexedSeq[Int] = IndexedSeq(1, 1, 2, 3)
Something goes wrong with escaping:
ReplyDelete&-
should be
<-
Thank you for noticing. It is fixed now
ReplyDelete