Collections Workbook


Practice problems for Kotlin Collections Are Read-Only Until You Say Otherwise. Each takes a minute or two. Write your own answer first, then click Show answer — nothing here is a trick question, just direct practice of the syntax from the lesson.

creating collections

1. A read-only list

Create a read-only list holding 1, 2, 3.

Show answer Hide answer
val numbers = listOf(1, 2, 3)

2. A mutable list

Create an empty mutable list of String and add "first" and "second".

Show answer Hide answer
val seen = mutableListOf<String>()
seen.add("first")
seen.add("second")

3. A set drops duplicates

What does setOf("a", "b", "a") contain?

Show answer Hide answer
setOf("a", "b", "a")   // {"a", "b"}

A Set holds each distinct value once.

4. A map

Create a read-only map from "Ada" to 36 and "Linus" to 54.

Show answer Hide answer
val ages = mapOf("Ada" to 36, "Linus" to 54)

reading and combining

5. A lookup that might miss

Given the map ages, look up "Ada". What’s the type of the result, and why?

Show answer Hide answer
val age: Int? = ages["Ada"]

It’s Int? — the key might be absent, so the type is nullable.

6. A lookup with a default

Look up "Nobody" in ages, falling back to 0 when the key is missing.

Show answer Hide answer
ages.getOrDefault("Nobody", 0)

7. Add without mutating

Given val numbers = listOf(1, 2, 3), produce a new list with 4 appended, leaving numbers unchanged.

Show answer Hide answer
val more = numbers + 4   // [1, 2, 3, 4]

8. Basic reads

Given val numbers = listOf(4, 8, 15), get its size, its first element, and whether it contains 8.

Show answer Hide answer
numbers.size        // 3
numbers.first()     // 4
8 in numbers        // true

mutability where it belongs

9. Build mutably, return read-only

Write labels(n: Int): List<String> that builds ["item 0", "item 1", …] with a mutable list internally but returns a read-only List.

Show answer Hide answer
fun labels(n: Int): List<String> {
    val result = mutableListOf<String>()
    for (i in 0 until n) result.add("item $i")
    return result
}

10. A counting map

Write count(words: List<String>): Map<String, Int> that tallies how many times each word appears, returning a read-only map.

Show answer Hide answer
fun count(words: List<String>): Map<String, Int> {
    val tally = mutableMapOf<String, Int>()
    for (word in words) {
        tally[word] = tally.getOrDefault(word, 0) + 1
    }
    return tally
}

11. A read-only view still changes

Write code that shows a read-only List reflecting a change made through the underlying MutableList it was assigned from — then take a stable snapshot.

Show answer Hide answer
val m = mutableListOf(1, 2)
val view: List<Int> = m
m.add(3)
println(view)   // [1, 2, 3] — same object, read-only interface

val snapshot = m.toList()   // an independent copy

Back to the lesson, Kotlin Collections Are Read-Only, or on to the next one: lambdas.