Search code examples
kotlinkotlin-delegate

Nested property delegation in Kotlin


As mentioned in the official tutorial, we can store properties in a Map and delegate a class to it:

class User(val map: Map<String, Any?>) {
    val name: String by map
    val age: Int     by map
}

However, sometimes we store non-trivial structures in a map, like another class (this is usual when working with complicated jsons). To better elaborate my idea, I came up with a pseudo-code like this:

class User(val map: Map<String, Any?>) {
    val name: String by map
    val otherType: OtherType by map
}

class OtherType {}

Is it possible to delegate such nested structure?


Solution

  • No problem, you can do this. It works:

    fun main(args: Array<String>) {
        val user = User(mapOf("name" to OtherType(1)))
        println(user)
    }
    
    data class User(val map: Map<String?, Any?>) {
        val name: String by map
        val otherType: OtherType by map
    }
    
    data class OtherType(val something:Int) {}
    

    You can delegate any type you want.