Map-backed delegated properties let you store and access object properties using a map. This helps when you want flexible or dynamic property storage without writing many variables.
0
0
Map-backed delegated properties in Kotlin
Introduction
When you want to create objects with properties that can change at runtime.
When you want to read or write properties from a map without manually coding each property.
When you want to easily convert JSON or other key-value data into Kotlin objects.
When you want to reduce boilerplate code for classes with many similar properties.
Syntax
Kotlin
import kotlin.reflect.KProperty class MapDelegate(val map: Map<String, Any?>) { operator fun <V> getValue(thisRef: Any?, property: KProperty<*>): V = (map[property.name] ?: error("No value for '${property.name}'")) as V } class MyClass(val map: Map<String, Any?>) { val prop: String by MapDelegate(map) }
The property is delegated to the map using by MapDelegate(map).
The map keys must match the property names exactly.
Examples
This class reads
name and age from the map keys.Kotlin
import kotlin.reflect.KProperty class MapDelegate(val map: Map<String, Any?>) { operator fun <V> getValue(thisRef: Any?, property: KProperty<*>): V = (map[property.name] ?: error("No value for '${property.name}'")) as V } class User(val map: Map<String, Any?>) { val name: String by MapDelegate(map) val age: Int by MapDelegate(map) }
Creates a map and accesses properties via the delegated properties.
Kotlin
val userData = mapOf("name" to "Anna", "age" to 28) val user = User(userData) println(user.name) // prints Anna println(user.age) // prints 28
Sample Program
This program creates a Person class with properties delegated to a map. It prints the person's full name and age.
Kotlin
import kotlin.reflect.KProperty class MapDelegate(val map: Map<String, Any?>) { operator fun <V> getValue(thisRef: Any?, property: KProperty<*>): V = (map[property.name] ?: error("No value for '${property.name}'")) as V } class Person(val map: Map<String, Any?>) { val firstName: String by MapDelegate(map) val lastName: String by MapDelegate(map) val age: Int by MapDelegate(map) } fun main() { val data = mapOf("firstName" to "John", "lastName" to "Doe", "age" to 30) val person = Person(data) println("Name: ${person.firstName} ${person.lastName}") println("Age: ${person.age}") }
OutputSuccess
Important Notes
If the map does not contain a key matching the property name, the program will throw an exception.
Map-backed properties are read-only by default. To make them mutable, you need a MutableMap and use var with delegation.
Summary
Map-backed delegated properties let you link class properties to map entries easily.
This reduces boilerplate when working with dynamic or flexible data.
Property names must match map keys exactly for this to work.