[Kotlin] Using Delegated Properties

img-header.a35685e862fa39ad24d32cce13e741f7330b330efc4d432bc5a14479e05ce7ec

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 click here

data class Model(val name: String, val preferences: 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 preferences: Map<String, Any?>) {
    val modelVersion: Int? by preferences // line 2
}

Now let’s try to understand what we have above.

  1. In our model, we added a map that can receive a key as String and an object with Any (the same as Object in Java)
  2. In the line number two what we are doing is to define a specific name and type that can be used in our map, this will allow us to do a few things out of the box:
    1. Access the map value by the property modelVersion
    2. Use the value as Int without having to declare cast

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", preferencies = mapOf("modelVersion" to 1))
    println(model)
    println(model.modelVersion)
    println(model.modelVersion == 1)
}

data class Model(val name: String, val preferencies: Map<String, Any?>) {
	val modelVersion: Int? by preferencies
}

// Output:
1. Model(name=Delegate, preferencies={modelVersion=1})
2. 1 
3. true
2 I like it
0 I don't like it

Leave a Reply

Your email address will not be published. Required fields are marked *