Menu
Coddy logo textTech

Nested Maps

Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 9 of 63.

A map value can itself be a map. Each lookup may be missing, so combine a safe call with a final fallback. Mutable updates require mutability at the level being changed.

Inside main:

val school = mapOf("Ada" to mapOf("math" to 9))
println(school["Ada"]?.get("art") ?: -1)

Ada exists, but the inner art key does not, so the fallback is used.

Use safe access at each map level that may be absent.

challenge icon

Challenge

Medium

Complete nestedScore with parameters name: String, subject: String. Use the fixed records Ada: math 9, art 7; Bo: math 6. Return the requested score or -1 when the name or subject is absent.

Unless stricter bounds are stated above, collections contain at most 100 elements at each level, and integer arguments and integer collection values are between -1000 and 1000. Text supplied for parsing can include invalid or out-of-range representations as described.

Return a value of type Int. Keep the supplied input/output code. It reads scalar arguments one per line; a list starts with its count followed by its elements, and a map starts with its entry count followed by each key and value. Nested lists repeat the count-and-elements format for each row. The supplied main prints the return value followed by one newline. Lists use Kotlin's standard bracketed format; print no additional labels.

Try it yourself

fun nestedScore(name: String, subject: String): Int {
    // Write your solution here.
    return 0
}
fun main() {
    val name = readLine().orEmpty()
    val subject = readLine().orEmpty()
    println(nestedScore(name, subject))
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Kotlin playground