Getting error while dealing with getter and setter

2019-03-04 04:45发布

问题:

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".