2021-03-14
[Kotlin] Using Delegated Properties
Usage of design patterns with Kotlin is one of the things that made me love the language, in this post, I am going to show how to use “Delegated Properties”.
Delegated Properties
To find out more about data classes:
https://kotlinlang.org/docs/delegated-properties.html
data class Model(val name: String, val data: Map<String, Any?> = mapOf())
Now what we want to do is have a specific property inside the map with a specific type.
data class Model(val name: String, val data: Map<String, Any?>) {
val modelVersion: Int? by data
}
Now let’s try to understand what we have above.
Few things to keep in mind in the moment of use Delegated properties, try to avoid have all properties of your model in a map otherwise, you will end a model based on a map.
Result
fun main(args: Array<String>) {
val model = Model(name = "Delegate", preferences = mapOf("modelVersion" to 1))
println(model)
println(model.modelVersion)
println(model.modelVersion == 1)
}
data class Model(val name: String, val preferences: Map<String, Any?>) {
val modelVersion: Int? by preferences
}
// Output:
1. Model(name=Delegate, preferences={modelVersion=1})
2. 1
3. true