https://kotlinlang.org logo
#getting-started
Title
# getting-started
l

Lokik Soni

11/06/2021, 12:58 PM
Hello everyone this is my first question in slack i.e I want to perform some operations on data class fields before accessing them to UI. For ex from Broadcast receiver I am passing battery temperature to the data class but the passed temperature format is not required by UI so i want to add logic to convert temperature from kelvin to celsius and hide the kelvin field from UI.
Copy code
data class BatteryProfile(
    private val _temperature: Int,
) {
    val temperature get() = logic to convert _temperature from kelvin to celsius

}
So i applied the above solution but i am feeling it is not good way also I have not seen data class primary constructor field as privete in any example. Please tell me if it is correct way or if wrong so how to achieve this.
s

Stephan Schroeder

11/06/2021, 1:22 PM
how about
Copy code
@JvmInline
value class Temperature private constructor(val inKelvin: Int) {
	val inCelsius: Int get()= temperatureInKelvin - 273
    
    override fun toString() = "${inKelvin}K"

    companion object {
        fun inCelsius(degreesInC: Int) = Temperature((degreesInC + 273).coerceAtLeast(0))

        fun inKelvin(degreesInK: Int) = Temperature( degreesInK.coerceAtLeast(0))
    }
}

data class BatteryProfile(
    val temperature: Temperature,
)