2

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?

0

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

kotlin loop variables(in your case i) are implicitly declared using val, so you can't reassign them. your only option is to use a while loop and update a variable declared outside the loop.

From Kotlin language spec

The for-loop is actually an overloadable syntax form with the following expansion:

for(VarDecl in C) Body is the same as

when(val $iterator = C.iterator()) {
    else -> while ($iterator.hasNext()) {
                val VarDecl = __iterator.next()
                <... all the statements from Body>
            } } ```

Comments

1

In Kotlin val variables are equivalent of Java's final, which means once assigned they cannot be changed. Use var instead when you want the variable to be reassigned. If possible, you should keep val to prevent accidental reassignment.

Example:

var a = 5

a = 4 // works

val b = 5

b = 4 // compiler error!

EDIT

The variable in for loop is treated as val by default, and you cannot change it. In order to achieve a loop with jumps, you need to use while loop instead.

3 Comments

read the question again, you don't have a specific var declaration when you are in a loop
I have edited the answer
That's not an exception. It's a compiler error.

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.