Mohammad Taqi
Mohammad Taqi

Reputation: 179

I want to use get set method in field of data class kotlin

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
        }
}

When _units receives the value, I want to assign that value to units (inside the model class) but, it isn't doing so here.

Actually, I want a variable in MyApplication modified in accordance with the value of the _units field.

How can I achieve that? Is there any way we can use get set method directly in field? like this(I know these is not correct but anything like these possible?)

data class Thermostat(
    // ... other properties

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

Any solution or any other way to do this type thing?.

Upvotes: 0

Views: 611

Answers (2)

Steyrix
Steyrix

Reputation: 3236

I suggest to avoid the idea of setting fields after creating instance of the data class. The point of data classes is to consistently contain data, and immutable data is usually safer than mutable.

I don't think that there is a point to store private data in a data class either (at least in your case), because data classes should not have logic. Your set method has side-effect, which is not a good practice. You should avoid side-logic in setters, do it separately. Nobody expects set method to do something else besides setting the value.

The easiest way to have an instance of the data class with up-to-date data is to create one in place.

Upvotes: 0

Meet Prajapati
Meet Prajapati

Reputation: 501

You need to remove the default initializer from the unit.

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

Usage :

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

Output :

Thermostat(_units=Fahrenheit)

Upvotes: 0

Related Questions