0
fun main() {
    val i = 1
    for (i in 1..10)
        println(i)
}

This prints numbers from 1 to 10 but the variable i is declared as val. Is this valid/possible?

Henry Twist
  • 5,666
  • 3
  • 19
  • 44
Nagaraj N
  • 457
  • 6
  • 13

1 Answers1

2

The outer i (val i = 1) is just being shadowed by the inner loop. The variables are different, so in answer to your question: yes it is possible and valid. You can verify this by printing after the loop:

val i = 1
for (i in 1..10) print(i)

println()
print(i)

which outputs:

12345678910
1

There's quite a good answer here which talks about why shadowing is a feature and why it can be useful.

Henry Twist
  • 5,666
  • 3
  • 19
  • 44