Delegating using map

4 0 0
                                        

Delegating a property using a map helper is commonly used in parsing JSON.

====================

fun main(){

    val obj = Practice1(mutableMapOf("prop1" to "Rimuru Tempest", "prop2" to "Slime"))

    println(obj.prop1)

    println(obj.prop2)

    obj.prop1 = "Veldora Tempest"

    obj.prop2 = "Dragon"

    println(obj.prop1)

    println(obj.prop2)

}

class Practice1(map: MutableMap<String, String>){

    val prop1: String by map,

    val prop2: String by map

}

===================

Result:

Rimuru Tempest

Slime

Veldora Tempest

Dragon


Note: Take note that the property name should be the same with the arguments when you invoke the mutableMapOf() to create an instance of it.

Kotlin ProgrammingWhere stories live. Discover now