Assume I have a data class:
data class SensorData(val name: String, val temp : Double)
I create this SensorData
object from either an REST service or by internal setter method, whereas name
is always populated and temp
might be empty.
Further on, I need this SensorData object through several classes, thats I thought of using a singleton
.
Obviously I need object
keyword as described here, but how can I combine data class object
?
You can use companion object to keep a reference to your data object:
data class SensorData(val name: String, var temp : Double) {
companion object {
@Volatile
@JvmStatic
private var INSTANCE: SensorData? = null
@JvmStatic
@JvmOverloads
fun getInstance(name: String = "default", temp : Double = 0.0): SensorData = INSTANCE ?: synchronized(this) {
INSTANCE ?: SensorData(name, temp).also { INSTANCE = it }
}
}
}
And use it like this:
val name1 = SensorData.getInstance("name", 5.0).name
// Or with default values:
val name2 = SensorData.getInstance().name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With