youngminz
youngminz

Reputation: 1434

The `val` in the for range is not immutable?

In documentation, val is assign-once (read-only) local variable. However, below is a for loop that assigns values to x several times. Is it a different concept than C++ const?

fun main(args: Array<String>) {
    val x = 6
    val y = 9
    for (x in 1..y) {
        println("fits in range $x")
    }
}

Output:

fits in range 1
fits in range 2
fits in range 3
fits in range 4
fits in range 5
fits in range 6
fits in range 7
fits in range 8
fits in range 9

Upvotes: 2

Views: 103

Answers (1)

Grzegorz Piwowarek
Grzegorz Piwowarek

Reputation: 13773

The x used in the range construct is shadowing the val x = 6 - those are two different variables in two different scopes.

You can see that yourself by writing:

val x = 6
val y = 9
for (x in 1..y) {
    println("fits in range $x")
}

println(x)

The last call will print the original value - 6

Upvotes: 5

Related Questions