Home > database >  Kotlin understanding missing var keyword in for loop
Kotlin understanding missing var keyword in for loop

Time:10-11

I am a beginner in Kotlin and going through for loop

Simple code sample:

 for (i in 1..5) print(i)

Please can someone advise me why we do not specify the counter/iterator variable type "i" with the keyword var / val. Since "var /val" is the standard way to declare variables in Kotlin.

CodePudding user response:

I cannot speak for the designers, but I believe that's a design decision to avoid unnecessary bloat.

You cannot use an existing variable as the loop variable. The loop variable is scoped to the loop, and shadows existing ones from outer scopes. Also, the loop variable can never be a val otherwise it wouldn't be able to change for each loop turn. So basically the dev would have no choice but to declare it as a var.

This means there is no real point in explicitly writing the var keyword here.

However I have to admit that the shadowing behaviour would be clearer if we had to write the var keyword here. That's a tradeoff that was considered in the design I guess.

  • Related