Initialization of an immutable variable inside a lambda, why there is no warning or error from the compiler?


#1

Let’s consider the following code:

class Foo {
    val bar: String
    val baz: MutableList<String> = ArrayList()

    init {
        with(baz) {
            bar = "bar"
            add(bar)
        }

        bar = "baz"
    }
}

fun main(args: Array<String>) {
    val foo = Foo()
    println(foo.bar)
    println(foo.baz)
}

The output is:
 baz
 [bar]

It seems to be a shadowing of the ‘bar’ variable but, It looks like I’m able to init an immutable variable several times.
So, I just wonder why there is no warning or error from the compiler?


#2

The lack of an error is a bug which will be fixed in Kotlin 1.1.3.