Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/65868521/initialize-variable-in-init-block-and-define-a-setter-for-the-variable-in-kotlin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...