5

How to increment for-loop variable dynamically as per some condition.

For example.

var col = 10

for (i <- col until 10) {

if (Some condition)
  i = i+2;   // Reassignment to val, compile error
  println(i)
}

How it is possible in scala.

3 Answers 3

2

Lots of low level languages allow you to do that via the C like for loop but that's not what a for loop is really meant for. In most languages, a for loop is used when you know in advance (when the loop starts) how many iterations you will need. Otherwise, a while loop is used.

You should use a while loop for that in scala.

var i = 0
while(i<10) {
    if (Some condition)
        i = i+2
    println(i)
    i+=1
}
Sign up to request clarification or add additional context in comments.

3 Comments

you shouldn't actually use var in scala unless is strictly necessary
@Painy James: how do you know whether using a var is strictly necessary?
@AdamMackler in any case in which performance is really critical. For instance, modifying a certain property of a object instead of copying it with that property changed.
0

If you dont want to use mutable variables you can try functional way for this

def loop(start: Int) {
    if (some condition) {
        loop(start + 2)
    } else {
        loop(start - 1) // whatever you want to do.
    }
}

And as normal recursion function you'll need some condition to break the flow, I just wanted to give an idea of what can be done.

Hope this helps!!!

Comments

-1

Ideally, you wouldn't use var for this. fold works pretty well with immutable values, whether it is an int, list, map...

It lets you set a default value (e.g. 0) to the variable you want to return and also iterate through the values(e.g i) changing that value (e.g accumulator) on every iteration.

val value = (1 to 10).fold(0)((loopVariable,i) => {    
   if(i == condition)
      loopVariable+1    
   else
      loopVariable 
})

println(value)

Example

2 Comments

Can you explain where the loop variable gets incremented?
The loop variable is the first argument fold accepts (we set that value to 0, you can set it to whatever you want). The second argument accepts a function with the loop variable and the current element of the iteration. Within that function you got the logic that increments or do whatever you want to do with the loop variable. I've change the naming on the example so you could understand it. Try to avoid var people, immutability is good stuff :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.