Yana Dior
Yana Dior

Reputation: 75

Kotlin understanding missing var keyword in for loop

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.

Upvotes: 3

Views: 451

Answers (1)

Joffrey
Joffrey

Reputation: 37710

This is simply how the for loop syntax is designed. I cannot speak for the designers, but I believe that's a design decision to avoid unnecessary bloat, and maybe confusion.

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. So it's kind of implied that you're declaring a new variable here, even without a keyword (however I have to admit that the shadowing behaviour would be clearer if we had to write the val/var keyword here).

Also, the loop variable is actually a val inside the loop's body (it cannot be reassigned), but it can feel like a var because it changes for each loop turn and is technically declared outside the loop's body. In effect, it's like a new val declared in the loop's body with a new value for each loop iteration.

So your example code can be thought of as:

var temp = 1
while (temp <= 5) {
    val i = temp
    println(i)
    temp++
}

That's probably why the designers decided to not put any keyword here: it's unnecessary, and both val and var would be confusing in their own way.

Upvotes: 6

Related Questions