CodeBlanks Logo Icon CodeBlanks

by map

Learn dynamic properties with by map.

by map delegation

You can delegate a property to a Map. Example: class User(val map: Map<String, Any?>) { val name: String by map; val age: Int by map }. Here name and age are read from map; the key is the property name.

This is handy for dynamic data: it makes key-value data like JSON accessible as a class. val properties delegate to a Map, var properties delegate to a MutableMap. For var the assignment map[name] = value works.

by map example

A User class is created with mapOf("name" to "Alex", "age" to 30). u.name reads the "name" key from the map and returns it as String. u.age returns 30.

Type safety matters: the age: Int declaration assumes the map value is an Int. A wrong type throws at runtime. Wrapping dynamic data with static types is the power of this pattern. With MutableMap, var properties can be both read and written.

Practice Define the User class with by map

Define class User(val map: Map<String, Any?>). Add val name: String by map and val age: Int by map properties inside. In main create User(mapOf("name" to "Alex", "age" to 30)) and call println(u.name) and println(u.age).

Starter code

Main.kt
// Define the User class: map parameter, name and age via map delegate

fun main() {
    // Create a User instance and print name, age
}

Sample solution

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

fun main() {
    val u = User(mapOf("name" to "Alex", "age" to 30))
    println(u.name)
    println(u.age)
}

Expected output

Alex
30

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the by map concepts

Term Meaning
by map Map delegation
map[key] Read value
var name by map Mutable
val name by map Read-only

2 What type does val name by map require?

  • List
  • Array
  • Set
  • Map Correct answer

Explanation: by map requires a Map; the key is the property name.

3 Complete the by map declaration

Question
class User(val map: Map<String, Any?>) {
    val name: String ____ map
}
Answer
class User(val map: Map<String, Any?>) {
    val name: String by map
}

Explanation: by map reads name from the map.

All lessons in Intermediate