Search code examples
androidkotlingetter-settergetter

Getting error while dealing with getter and setter in kotlin


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.


Solution

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