Getting error while dealing with getter and setter in kotlin

后端 未结 2 1967
粉色の甜心
粉色の甜心 2021-01-26 05:26

I have define the data class as:

  data class chatModel(var context:Context?) {

      var chatManger:ChatManager?=null
            //getter
        get() = chat         


        
相关标签:
2条回答
  • 2021-01-26 06:03

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

    0 讨论(0)
  • 2021-01-26 06:19

    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.

    0 讨论(0)
提交回复
热议问题