Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize variable in init block and define a setter for the variable in kotlin

I want to write this piece of code but it doesn't work.

private var a: Int
    set(value) {
        field = a
        // Code
    }

init {
    a = 2
}

I have to initialitze the variable when I declare it. Why does it happen? How can I solve it?

like image 711
Marti Serra Molina Avatar asked Nov 19 '25 23:11

Marti Serra Molina


1 Answers

Your property has a custom setter, and when you call a = 2 in the init block, that setter's code will run.

That code could be arbitrarily complex, and the compiler can't know for sure whether it will end up setting the value of the backing field of the property or not. In your code example, it would set the backing field, and your property would be in a valid state.

However, you could also have a custom setter such as this one:

private var a: Int
    set(value) {
        if (value > 0) {
            field = value
        }
    }

Calling this in an init block would not necessarily would be enough, as it might leave the property in an uninitialized state.

To prevent this, the compiler asks you to set a value to the property at its declaration instead when using custom setters.

like image 135
zsmb13 Avatar answered Nov 21 '25 14:11

zsmb13



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!