In Scala, what if I have a nested for loop, and I want to execute different things on each one.
for (int i = 0; i<5; i++) {
System.out.println(i); //do something for just i
for(int j = 0; j<5; j++) {
System.out.println(i+j); //do something for both i and j
}
}
But the scala code:
for {i<-0 to 5
j<- 0 to 5} yield { print(i); print(i+j)}
gives the output:
0
(0,0)
0
(0,1)
0
(0,2)
0
(0,3)
0
(0,4)
0
(0,5)
but I want it to be:
0
(0,0)
(0,1)
(0,2)
(0,3)
(0,4)
(0,5)
Is there a way to only print i for each i, and i+j for each i and j in ONE for loop?
if (j == 0) print(i); print(i+j);.. not very clean, as side-effects. Why not just a nested loop? You can still use the "x <- a to b" syntax for the range.for{...} {...}is for-loop.for{...} yield {...}is for-comprehension. They are very different things.