SDSnipDojo
← All lessons
Lesson 09 / 126 steps3 exercises

Collections

Lists, plus the workhorses map and filter.

1. Lists

Use listOf(...) to make an immutable list. Index with [i]; get the size with .size:

val nums = listOf(10, 20, 30)
nums[0]                 // 10
nums.size               // 3

List<T> is a generic type — List<Int>, List<String>, etc.

2. firstWord

Implement firstWord(parts) returning the first element of the list. Assume the list has at least one item.

Starter code

fun firstWord(parts: List<String>): String {
    return ""
}

3. map — transform each element

.map { ... } returns a new list with the lambda applied to every element. it refers to the current element:

listOf(1, 2, 3).map { it * 2 }                 // [2, 4, 6]
listOf("ada", "bob").map { it.uppercase() }    // [ADA, BOB]

The result type is whatever the lambda returns — List<Int>.map { it.toString() } gives you a List<String>.

4. doubles with map

Implement doubles(nums) returning each number multiplied by 2. Use .map { it * 2 }.

Starter code

fun doubles(nums: List<Int>): List<Int> {
    return nums
}

5. filter — keep matching elements

.filter { ... } returns a new list with only the elements where the lambda returns true:

listOf(1, 2, 3, 4).filter { it > 2 }        // [3, 4]
listOf(1, 2, 3, 4).filter { it % 2 == 0 }   // [2, 4]

map and filter chain naturally — they always return a new list, never mutate the original:

listOf(1, 2, 3, 4).filter { it % 2 == 0 }.map { it * 10 }   // [20, 40]

6. evens with filter

Implement evens(nums) returning only the even numbers from the input list, preserving order. Use .filter { it % 2 == 0 }.

Starter code

fun evens(nums: List<Int>): List<Int> {
    return nums
}

Run this Kotlin lesson in your browser

SnipDojo ships an in-browser Kotlin editor with the exercises above already wired to tests. Sign in with Google to edit the starter code, run it, and track your progress toward the free certificate — no installs and no local toolchain.

Sign in to run this code →