Bird
Raised Fist0
Kotlinprogramming~20 mins

Map-backed delegated properties in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Map Delegation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of map-backed delegated properties with default values
What is the output of this Kotlin code using map-backed delegated properties?
Kotlin
class User(val map: Map<String, Any?>) {
    val name: String by map
    val age: Int by map
}

fun main() {
    val user = User(mapOf("name" to "Alice", "age" to 30))
    println("Name: ${user.name}, Age: ${user.age}")
}
ACompilation error due to missing property
BName: Alice, Age: 30
CName: null, Age: 30
DName: Alice, Age: null
Attempts:
2 left
💡 Hint
The delegated properties read values from the map by their keys.
❓ Predict Output
intermediate
2:00remaining
Behavior when map key is missing in map-backed delegated properties
What happens when a delegated property tries to access a missing key in the map?
Kotlin
class User(val map: Map<String, Any?>) {
    val name: String by map
    val age: Int by map
}

fun main() {
    val user = User(mapOf("name" to "Bob"))
    println("Name: ${user.name}, Age: ${user.age}")
}
AThrows NoSuchElementException at runtime
BName: Bob, Age: null
CCompilation error due to missing key
DName: Bob, Age: 0
Attempts:
2 left
💡 Hint
Accessing a missing key in the map throws an exception when using map delegation.
🔧 Debug
advanced
2:00remaining
Identify the runtime error in map-backed delegated properties
What runtime error occurs when running this Kotlin code?
Kotlin
class User(val map: Map<String, Any?>) {
    val name: String by map
    val age: Int by map
}

fun main() {
    val user = User(mapOf("name" to "Charlie", "age" to "thirty"))
    println("Name: ${user.name}, Age: ${user.age}")
}
ANoSuchElementException due to missing key
BNullPointerException due to null value
CClassCastException due to wrong type for 'age'
DCompilation error due to type mismatch
Attempts:
2 left
💡 Hint
The map contains a String for 'age' but the property expects an Int.
📝 Syntax
advanced
2:00remaining
Correct syntax for mutable map-backed delegated properties
Which option correctly declares mutable map-backed delegated properties in Kotlin?
Kotlin
class User(val map: MutableMap<String, Any?>) {
    var name: String by map
    var age: Int by map
}
A
val name: String by mutableMapOf()
val age: Int by mutableMapOf()
B
val name: String by map
val age: Int by map
C
var name: String by map.toMap()
var age: Int by map.toMap()
D
var name: String by map
var age: Int by map
Attempts:
2 left
💡 Hint
Mutable properties require var and a mutable map for delegation.
🚀 Application
expert
2:00remaining
How many entries are in the map after property mutation?
Given this Kotlin code, how many entries does the map contain after the mutation?
Kotlin
fun main() {
    val data = mutableMapOf<String, Any?>("name" to "Dana", "age" to 25)
    class User(val map: MutableMap<String, Any?>) {
        var name: String by map
        var age: Int by map
    }
    val user = User(data)
    user.age = 26
    user.name = "Dana S."
    println(data.size)
}
A2
B3
C1
D0
Attempts:
2 left
💡 Hint
Mutating delegated properties updates existing map entries, not adding new ones.

Practice

(1/5)
1. What is the main purpose of using Map-backed delegated properties in Kotlin?
easy
A. To convert maps into JSON strings automatically
B. To link class properties directly to entries in a map
C. To perform arithmetic operations on map values
D. To create immutable lists easily

Solution

  1. Step 1: Understand the concept of map-backed delegation

    Map-backed delegated properties allow class properties to get and set values directly from a map using the property name as the key.
  2. Step 2: Identify the main purpose

    This reduces boilerplate code when working with dynamic data by linking properties to map entries.
  3. Final Answer:

    To link class properties directly to entries in a map -> Option B
  4. Quick Check:

    Map-backed delegation links properties to map keys [OK]
Hint: Remember: properties match map keys exactly [OK]
Common Mistakes:
  • Thinking it creates immutable lists
  • Assuming it converts maps to JSON
  • Confusing it with arithmetic operations on maps
2. Which of the following is the correct syntax to declare a property name delegated to a map map in Kotlin?
easy
A. val name by map["name"]
B. val name = map["name"]
C. val name by map.get("name")
D. val name by map

Solution

  1. Step 1: Recall the syntax for map-backed delegated properties

    In Kotlin, you delegate a property to a map using val property by map, where the property name matches the map key.
  2. Step 2: Analyze each option

    val name by map uses the correct syntax. val name by map["name"] tries to delegate to a map entry, which is invalid. val name by map.get("name") calls a function, not delegation. val name = map["name"] just assigns the value, not delegation.
  3. Final Answer:

    val name by map -> Option D
  4. Quick Check:

    Property delegation uses 'by map' syntax [OK]
Hint: Use 'by map' with property name matching key [OK]
Common Mistakes:
  • Trying to delegate to map entry like map["key"]
  • Using map.get() instead of delegation
  • Assigning value directly without delegation
3. What will be the output of the following Kotlin code?
class User(val map: Map<String, Any?>) {
    val name: String by map
    val age: Int by map
}

fun main() {
    val user = User(mapOf("name" to "Alice", "age" to 30))
    println("Name: ${user.name}, Age: ${user.age}")
}
medium
A. Name: Alice, Age: 30
B. Name: null, Age: 0
C. Compilation error due to type mismatch
D. Runtime exception due to missing keys

Solution

  1. Step 1: Understand map-backed delegation behavior

    The properties name and age delegate to the map keys "name" and "age" respectively, retrieving their values.
  2. Step 2: Check the map contents and output

    The map contains "name" as "Alice" and "age" as 30, so printing these properties outputs "Name: Alice, Age: 30".
  3. Final Answer:

    Name: Alice, Age: 30 -> Option A
  4. Quick Check:

    Map keys match properties, so values print correctly [OK]
Hint: Property names must match map keys exactly [OK]
Common Mistakes:
  • Expecting null or default values
  • Confusing delegation with direct assignment
  • Assuming runtime error without missing keys
4. Identify the error in this Kotlin code using map-backed delegated properties:
class Person(val map: Map<String, Any>) {
    val firstName: String by map
    val lastName: String by map
}

fun main() {
    val data = mapOf("firstName" to "John")
    val person = Person(data)
    println(person.lastName)
}
medium
A. No error; prints null for missing key
B. Compilation error because map type is incorrect
C. Runtime exception due to missing key "lastName" in map
D. Syntax error in property delegation

Solution

  1. Step 1: Check map keys vs delegated properties

    The map contains only "firstName", but the class expects both "firstName" and "lastName" keys for delegation.
  2. Step 2: Understand behavior on missing keys

    Accessing person.lastName tries to get a missing key, causing a runtime exception (NoSuchElementException).
  3. Final Answer:

    Runtime exception due to missing key "lastName" in map -> Option C
  4. Quick Check:

    Missing map keys cause runtime errors [OK]
Hint: All delegated keys must exist in the map [OK]
Common Mistakes:
  • Assuming missing keys return null
  • Thinking it's a compile-time error
  • Ignoring runtime exceptions on missing keys
5. Given a map data = mapOf("x" to 10, "y" to 20, "z" to 0), how can you create a Kotlin class Point with map-backed delegated properties x, y, and z but only expose x and y publicly, hiding z internally?
hard
A. Declare val x: Int by map, val y: Int by map as public and private val z: Int by map
B. Declare all properties as val without visibility modifiers
C. Use var for z and val for others
D. Exclude z from the map passed to the class

Solution

  1. Step 1: Understand visibility modifiers in Kotlin

    Properties can be declared with private to hide them from outside the class.
  2. Step 2: Apply visibility to map-backed properties

    Declare x and y as public (default) and z as private val z: Int by map to hide it internally.
  3. Final Answer:

    Declare val x: Int by map, val y: Int by map as public and private val z: Int by map -> Option A
  4. Quick Check:

    Use 'private' modifier to hide delegated properties [OK]
Hint: Use 'private' keyword to hide properties [OK]
Common Mistakes:
  • Assuming all properties are public by default
  • Trying to exclude keys from the map instead of hiding
  • Confusing var and val for visibility
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard