I
I
Ilya Kolpakov2020-12-21 19:33:14
Kotlin
Ilya Kolpakov, 2020-12-21 19:33:14

Why doesn't this code throw a "Val cannot be reassigned" error?

I saw this example in the article https://habr.com/ru/company/funcorp/blog/425943/ . The author of the article wrote that he did not know how the constant (val) changes the value, and that this is probably a mistake. Maybe this is a stupid question, but I really want to figure out what exactly happens to a variable when a new object is created, how val testParam takes on different values.

The program outputs:
"in showTestParam testParam = some string"
"in constructor testParam = after"

class MyClassB {

    init {
        testParam = "some string"
        showTestParam()
    }

    init {
        testParam = "new string"
    }

    val testParam: String = "after"

    constructor(){
        println("in constructor testParam = $testParam")
    }

    fun showTestParam(){
        println("in showTestParam testParam = $testParam")
    }
}

fun main() {
    val classB = MyClassB()}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2020-12-21
@zagayevskiy

Never thought much about it. Apparently, they partly copied the behavior from Java, and partly simply made a mistake in the design of the language at an early stage of design. And now we must support it. I see no reason to do this, control flow analysis allows you to avoid reassignment. By the way, if you call showTestParam() at the very beginning of the first init block, there will also be null :(

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question