Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the counter variable value of for loop inside the loop in Kotlin?

I'm new to Kotlin and for practice i'm converting my Java codes into Kotlin.

While doing that I'm facing one issue i.e., i'm unable to change the counter value inside the for loop. It actually says the variable is val.

for (i in 0..tokens.size){
    // some code
    if (memory[pointer]!=0)
        i=stack.peek() // error here showing : val cannot be reassigned
}

I really want the counter variable to be changed inside the loop. Is there any other way that i can achieve this without any error in Kotlin?

like image 488
Ruthvik Avatar asked Dec 18 '25 16:12

Ruthvik


1 Answers

Note that for...in loop is not a loop with counter, but a foreach loop - even if you use range to iterate (well, at least conceptually, because internally it is in fact optimized to a loop with counter). You can't jump to another item in the array/list, because for does not really "understand" the logic behind iterating. Even if you would be able to modify the value of i, then with next iteration it would reset to the next item.

You need to use while instead:

var i = 0
while (i < tokens.size) {
    if (memory[pointer]!=0)
        i=stack.peek()

    i++
}

Also note that your original code contained an off-by-one bug. In last iteration i would become tokens.size which is probably not what you need.

like image 153
broot Avatar answered Dec 22 '25 00:12

broot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!