cYn
cYn

Reputation: 3381

Increment for-loop by 2 in Scala

How do I increment the loop by 2 as equivalent to this in Java:

for (int i = 0; i < max; i+=2)

Right now in Scala I have:

for (a <- 0 to max)

For a fact max will always be even. I don't know how to increment the counter to 2 in each loop.

Upvotes: 47

Views: 30872

Answers (6)

claydonkey
claydonkey

Reputation: 159

Surely

(0 until max by 2)  foreach {...}

will suffice.

Upvotes: 4

Nilesh Shinde
Nilesh Shinde

Reputation: 461

This way you can use scala for loop like java one.

object Example extends App {
    for(i <-0 to 20 by 2) {
        println("Value of i = "+ i)
    }
}

Output

Value of i = 0
Value of i = 2
Value of i = 4
Value of i = 6
Value of i = 8
Value of i = 10
Value of i = 12
Value of i = 14
Value of i = 16
Value of i = 18
Value of i = 20

Upvotes: 4

om-nom-nom
om-nom-nom

Reputation: 62835

Unsurprisingly easy:

scala> for (a <- 0 until 10 by 2) yield a
// Vector(0, 2, 4, 6, 8, 10)

Upvotes: 1

tkroman
tkroman

Reputation: 4798

Try for (a <- 0 until max by 2)

Upvotes: 82

Brian
Brian

Reputation: 20285

Note the difference between to and until. With a strict i < max you will want until.

val max = 10

scala> for(i <- 0 until max by 2)
     | println(i)
0
2
4
6
8

scala> for(i <- 0 to max by 2)
     | println(i)
0
2
4
6
8
10

Upvotes: 24

Vorsprung
Vorsprung

Reputation: 34297

for (a <- 0 to max by 2) yield a

Upvotes: 1

Related Questions