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?
CodePudding user response:
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.
CodePudding user response:
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> } } ```
CodePudding user response:
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.