Getting error while dealing with getter and setter in kotlin

我是研究僧i 提交于 2019-12-02 21:19:23

问题


I have define the data class as:

  data class chatModel(var context:Context?) {

      var chatManger:ChatManager?=null
            //getter
        get() = chatManger
            //setter
        set(value) {
            /* execute setter logic */
            chatManger = value
        }

    }

Now how will i access the get() and set() function. In java I do like that: //for getter

new chatModel().getJId()

//for setter

new chatModel().setJId("jid")

edit:

As the @yole suggested. I am using setter and getter as:

//set the data

var chatDetails:chatModel=chatModel(mApplicationContext)
 chatDetails.chatManger=chatManager

But end up getting the java.lang.StackOverflowError: at

com.example.itstym.smackchat.Model.chatModel.setChatManger(chatModel.kt:38)

line 38 points to

chatManger = value

this.

@RobCo suggested.

I have change the data class definition as:

data class chatModel(var context: Context?) {


    var chatManger:ChatManager

    get() = field
    set(value) {
        field=value
    }
}

//set the data.

    chatModel(mApplicationContext).chatManger=chatManager

//get the data in different activity

chatModel(applicationContext).chatManger

but getting error property must be initialized. If I assigned it to null then I am getting null not the set value.


回答1:


You call the setter inside of the setter.. a.k.a. infinite loop:

    set(value) {
        /* execute setter logic */
        chatManger = value
    }

Inside a property getter or setter there is an additional variable available: field. This represents the java backing field of that property.

    get() = field
    set(value) {
        field = value
    }

With a regular var property, these getters and setters are auto-generated. So, this is default behaviour and you don't have to override getter / setter if all you do is set the value to a field.




回答2:


It is important to remember that referring to chatManger ANYWHERE in the code ends up calling getChatManger() or setChatManger(), including inside of the getter or setter itself. This means your code will end up in an infinite loop and cause a StackOverflowError.

Read up on Properties, specifically the section about getters/setters as well as the "backing field".



来源:https://stackoverflow.com/questions/43465032/getting-error-while-dealing-with-getter-and-setter-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!