在Kotlin中处理getter和setter时出错 [英] Getting error while dealing with getter and setter in kotlin

查看:362
本文介绍了在Kotlin中处理getter和setter时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将数据类定义为:

  data class chatModel(var context:Context?) {

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

    }

现在我将如何访问get()和set()函数. 在Java中,我喜欢这样: //对于吸气剂

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

new chatModel().getJId()

//对于二传手

new chatModel().setJId("jid")

如@yole建议.我正在使用setter和getter作为:

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

//设置数据

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

但是最终在

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

第38行指向

chatManger = value

这个.

@RobCo建议.

我将数据类定义更改为:

I have change the data class definition as:

data class chatModel(var context: Context?) {


    var chatManger:ChatManager

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

//设置数据.

    chatModel(mApplicationContext).chatManger=chatManager

//获取不同活动中的数据

//get the data in different activity

chatModel(applicationContext).chatManger

,但必须初始化获取错误"属性.如果我将其分配为null,那么我将获得null而不是设置值.

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

推荐答案

您可以在设置器内部调用设置器..a.k.a.无限循环:

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

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

在属性获取器或设置器中,还有一个可用的附加变量:field.这表示该属性的Java 后备字段.

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
    }

使用常规的var属性,可以自动生成这些getter和setter. 因此,这是默认行为,如果您所做的只是将值设置为字段,则不必覆盖getter/setter.

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.

这篇关于在Kotlin中处理getter和setter时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆