我想在数据类kotlin的字段中使用get set方法

问题描述 投票:0回答:1
data class Thermostat(
    // ... other properties

    @SerializedName("units")
    private var _units: String?, // Fahrenheit,

    // ... other properties
) : Serializable {
    var units: String? = null
        get() = _units
        set(value) {
            MyApplication.temperatureServerIsCelsius = (!value?.equals("Fahrenheit")!!)
            _units = value
        }
}

当 _units 收到值时,我想将该值分配给单位(在模型类内),但是这里没有这样做。

实际上,我想根据_units字段的值修改MyApplication中的一个变量。

我怎样才能实现这一目标? 有什么办法可以在字段中直接使用get set方法吗? 像这样(我知道这些不正确,但类似的事情可能吗?)

data class Thermostat(
    // ... other properties

    @SerializedName("units")
    private var _units: String?
       get() = _units
       set(value) {
                MyApplication.temperatureServerIsCelsius = 
                (!value?.equals("Fahrenheit")!!)
            }
    )

有任何解决方案或任何其他方法来执行此类操作吗?

android kotlin getter-setter jsonserializer data-class
1个回答
0
投票

您需要从

unit
中删除默认初始化程序。

data class Thermostat(
    private var _units: String?, // Fahrenheit,
) {
    var units: String?
        get() = _units
        set(value) {
            _units = value
        }
}

用途:

 val s = Thermostat(null)
    s.units = "Fahrenheit"
    println(s)

输出:

Thermostat(_units=Fahrenheit)
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.