Skip to content
LumenaryAcademy
Practice 55 min

Collections, sequences and scope functions

Read-only and mutable collections, the standard library's rich set of transformations, lazy sequences, and the five scope functions and when to use each.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

Saying what you want done to the data

Ask experienced Kotlin developers what they would miss most if they went back to another language, and many will name the collection library. A question such as "revenue per city, for the cities with more than a hundred sales, sorted highest first" becomes a chain of four or five named operations that reads almost like the question itself. There are well over a hundred such functions, every one an extension function on the standard collection interfaces, and every one available on Java's collection classes too, because Kotlin's collections are Java's collections viewed through Kotlin interfaces.

This lesson covers three things: the collection types and the difference between read-only and mutable; the transformations you will use daily; and sequences, Kotlin's lazy collections, which change how much work a pipeline does. It ends with the scope functions (let, run, with, apply, also), five small functions that appear in almost every Kotlin file and that confuse almost every newcomer until someone draws them in a table.

DefinitionsH

Collection types

Definition— Read-only and mutable collections

Kotlin has two interfaces for each kind of collection: read-only List, Set and Map, which have no methods that change them, and MutableList, MutableSet and MutableMap, which extend them with add, remove, put and so on. listOf, setOf and mapOf return read-only views; mutableListOf, mutableSetOf and mutableMapOf return mutable ones. On the JVM, both are backed by ordinary Java collections such as ArrayList, LinkedHashSet and LinkedHashMap.

Definition— Read-only is not immutable

A read-only reference promises that you will not change the collection through it. Someone holding a mutable reference to the same collection still can. Truly immutable collections are available from the separate kotlinx.collections.immutable library.

Definition— Sequence

A lazily evaluated collection: operations on a Sequence are recorded, not run, until a terminal operation such as toList, first or sum asks for results. Then each element passes through the whole pipeline before the next one starts. Kotlin's sequences play the role of Java's streams, but can be iterated more than once if their source allows it.

Two facts make Kotlin's sets and maps pleasant to use: setOf and mapOf preserve insertion order (they are backed by LinkedHashSet and LinkedHashMap), and maps support indexing syntax, prices["tea"], which returns null for a missing key, and prices["tea"] = 4 for mutable maps.

Worked examplesH

Transformations you will use every day

The data: a week of sales at a small tea and coffee wholesaler, in three Kenyan cities.

kotlin
data class Sale(val city: String, val product: String, val units: Int, val unitPrice: Int)

fun main() {
    val sales = listOf(
        Sale("Nairobi", "tea", 40, 3),
        Sale("Mombasa", "coffee", 25, 5),
        Sale("Nairobi", "coffee", 10, 5),
        Sale("Kisumu", "tea", 30, 3),
        Sale("Mombasa", "tea", 15, 3),
        Sale("Nairobi", "cocoa", 5, 8),
    )

    val revenue = sales.sumOf { it.units * it.unitPrice }
    println("total revenue: $revenue")

    // groupBy: a Map from key to the list of matching elements
    val byCity: Map<String, List<Sale>> = sales.groupBy { it.city }
    println(byCity.mapValues { (_, list) -> list.sumOf { it.units * it.unitPrice } })

    // associate: one entry per element (later keys overwrite earlier ones)
    val priceOf = sales.associate { it.product to it.unitPrice }
    println(priceOf)

    // partition, sortedWith, take
    val (big, small) = sales.partition { it.units >= 25 }
    println("${big.size} big, ${small.size} small")
    val ranking = sales.sortedWith(compareByDescending<Sale> { it.units * it.unitPrice }.thenBy { it.city })
    println(ranking.take(3).map { "${it.city}/${it.product}" })

    // fold: build one result from all elements
    val unitsPerProduct = sales.fold(mutableMapOf<String, Int>()) { acc, s ->
        acc[s.product] = (acc[s.product] ?: 0) + s.units
        acc
    }
    println(unitsPerProduct)

    // Windows, chunks, zips and flattening
    val daily = listOf(12, 15, 9, 20, 22, 18, 25)
    println(daily.windowed(3).map { it.average() })
    println(daily.chunked(3))
    println(daily.zipWithNext { a, b -> b - a })
    println(listOf("ab", "cde").flatMap { it.toList() })

    // Read-only and mutable interfaces; building a list
    val readOnly: List<Int> = listOf(1, 2, 3)
    val mutable: MutableList<Int> = readOnly.toMutableList()
    mutable += 4
    val squares = buildList { for (i in 1..5) add(i * i) }
    println("$readOnly $mutable $squares")
    println(squares.maxByOrNull { it % 7 } to squares.firstOrNull { it > 100 })
}
text
total revenue: 470
{Nairobi=210, Mombasa=170, Kisumu=90}
{tea=3, coffee=5, cocoa=8}
3 big, 3 small
[Mombasa/coffee, Nairobi/tea, Kisumu/tea]
{tea=85, coffee=35, cocoa=5}
[12.0, 14.666666666666666, 17.0, 20.0, 21.666666666666668]
[[12, 15, 9], [20, 22, 18], [25]]
[3, -6, 11, 2, -4, 7]
[a, b, c, d, e]
[1, 2, 3] [1, 2, 3, 4] [1, 4, 9, 16, 25]
(4, null)

A tour of what each does, grouped by purpose:

PurposeFunctionsIn the program
AggregatesumOf, count, maxByOrNull, average, fold, reducetotal revenue; units per product
Group and indexgroupBy (key to list), associate/associateBy (key to one value), partition (two lists)revenue per city; price per product
Ordersorted, sortedBy, sortedWith(compareBy(...).thenBy(...)), reversedthe top three sales
Reshapewindowed, chunked, zip, zipWithNext, flatMap, flattenmoving averages; day-to-day changes
Findfirst, firstOrNull, find, any, all, none, indexOfFirstthe first square over 100 (none)

Some details that matter in real code:

  • groupBy versus associate. groupBy keeps every element under its key; associate (and associateBy, associateWith) keeps one value per key, and when keys repeat, the last one wins. Here every product has one price, so that is harmless; for counting, use groupingBy { it.product }.eachCount() or groupBy.
  • Destructuring in lambdas. mapValues { (_, list) -> ... } takes each map entry apart; _ ignores the key.
  • Comparator builders. compareByDescending<Sale> { ... }.thenBy { it.city } sorts by revenue, highest first, and breaks ties by city. Writing comparisons by hand is a classic source of bugs; these builders avoid it.
  • OrNull variants. maxByOrNull and firstOrNull return null for "nothing found" instead of throwing, which fits Kotlin's null safety. The to in the last line builds a Pair, which prints in parentheses.
  • buildList gives you a mutable list inside the lambda and returns it as a read-only List, a tidy way to build a collection with loops and conditions.

All of these return new collections; none changes the original. On a list, each operation runs immediately over the whole collection and allocates its result. That is usually exactly what you want, and it is fast, because these functions are inline and their lambdas compile to plain loops. When it is not what you want, use a sequence.

ComputationC

Sequences: lazy pipelines

kotlin
fun isPrime(n: Int): Boolean = n >= 2 && (2..n).takeWhile { it * it <= n }.none { n % it == 0 }

fun main() {
    val words = listOf("amber", "basalt", "cobalt", "dune", "ember", "flint")
    var steps = 0

    // A list pipeline is eager: each step processes the whole list and builds a new list
    steps = 0
    val eager = words.map { steps++; it.uppercase() }.filter { steps++; it.length == 6 }.first()
    println("eager: $eager after $steps steps")

    // A sequence is lazy: each element goes through the whole pipeline, and work stops when done
    steps = 0
    val lazy = words.asSequence().map { steps++; it.uppercase() }.filter { steps++; it.length == 6 }.first()
    println("lazy:  $lazy after $steps steps")

    // Infinite sequences are fine, as long as something limits them
    val primes = generateSequence(2) { it + 1 }.filter(::isPrime)
    println(primes.take(10).toList())
    println(primes.first { it > 1_000 })

    // The sequence builder: yield values one at a time from ordinary code
    val fibonacci = sequence {
        var a = 0L
        var b = 1L
        while (true) {
            yield(a)
            val next = a + b
            a = b
            b = next
        }
    }
    println(fibonacci.take(12).joinToString())
    println(fibonacci.dropWhile { it < 1_000_000 }.first())
}
text
eager: BASALT after 12 steps
lazy:  BASALT after 4 steps
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
1009
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
1346269

The eager pipeline uppercased all six words (6 steps), then filtered all six (6 more), and only then took the first. The lazy one took "amber" through map and filter (2 steps; rejected), then "basalt" (2 steps; accepted), and stopped: 4 steps. With six words the difference is trivial; with a million records read from a file, or an expensive operation in the map, it is the difference between instant and minutes.

Laziness also makes infinite sequences possible. generateSequence(2) { it + 1 } describes all integers from 2 upwards; nothing is computed until take(10).toList() or first { ... } asks, and they ask for only as much as they need. The sequence { ... } builder lets you write a generator as ordinary code with loops and local variables, handing out values with yield. Each yield suspends the block until the consumer asks for the next value. That suspension is done with the same machinery as Kotlin's coroutines, the subject of Coroutines and structured concurrency.

When to use which. Use plain list operations by default: for small and medium collections they are simpler and usually faster, since each step is a tight loop. Reach for asSequence() when the pipeline is long and the data large, when you stop early (first, take, any), when the source is infinite or generated, or when intermediate lists would waste a lot of memory. Sequences have per-element overhead, so measure if performance matters.

Worked examplesH

The scope functions

Five standard functions run a block of code "in the context of" an object. They differ in two ways: how the block refers to the object (this or it) and what the call returns (the object itself, or the block's result).

FunctionObject in the blockReturnsTypical use
applythisthe objectconfigure a new object
alsoitthe objecta side effect, such as logging, in the middle of a chain
letitthe block's resulttransform a value, especially after ?.
runthisthe block's resultcompute something from an object's members
with(x)thisthe block's resultlike run, with the object as an argument
kotlin
class Email {
    var to: String = ""
    var subject: String = ""
    val body = StringBuilder()
    override fun toString() = "To: $to | Subject: $subject | ${body.length} chars"
}

fun findDiscountCode(customer: String): String? = if (customer.startsWith("A")) "WELCOME10" else null

fun main() {
    // apply: configure an object (this = the object), returns the object
    val mail = Email().apply {
        to = "amara@example.org"
        subject = "Your order"
        body.append("Thank you for your order.")
    }
    println(mail)

    // also: do something extra with a value (it = the value), returns the value
    val numbers = mutableListOf(3, 1, 2).also { println("before sorting: $it") }
    numbers.sort()

    // let: transform a value, most often a nullable one (it = the value), returns the lambda result
    for (customer in listOf("Amara", "Bao")) {
        val line = findDiscountCode(customer)?.let { code -> "$customer gets $code" } ?: "$customer gets no code"
        println(line)
    }

    // run: compute something using an object's members (this = the object), returns the lambda result
    val summary = mail.run { "$subject for $to" }
    println(summary)

    // with: the same as run, but the object is an argument rather than a receiver
    val stats = with(numbers) { "min=${first()} max=${last()} sum=${sum()}" }
    println(stats)

    // takeIf / takeUnless: keep a value only if a condition holds, otherwise null
    val port = "8080".toIntOrNull()?.takeIf { it in 1..65_535 } ?: 80
    val badPort = "99999".toIntOrNull()?.takeIf { it in 1..65_535 } ?: 80
    println("$port $badPort")
}
text
To: amara@example.org | Subject: Your order | 25 chars
before sorting: [3, 1, 2]
Amara gets WELCOME10
Bao gets no code
Your order for amara@example.org
min=1 max=3 sum=6
8080 80

How to remember them: apply and also return the object, so they fit in the middle of building or passing something along ("create an email, and apply these settings"; "make the list, and also log it"). let, run and with return the block's result, so they produce something new. Among those, let is the one for nullable values (x?.let { ... }), and run/with are for using many members of one object without repeating its name. takeIf returns the value if the condition holds and null otherwise, which combines neatly with ?: for validation with a fallback, as in the port example.

Scope functions are easy to overuse. Nesting them (an apply inside a let inside a run) makes this and it refer to different things on different lines, and a plain local variable is often clearer. A good rule: use one when it removes a temporary variable or a repeated name, and never nest more than one level.

ExplanationH

Collections in real codebases

Expose read-only types, keep mutable ones private. The pattern you saw in Playlist in the previous lesson is everywhere in professional Kotlin: a class keeps a private val items = mutableListOf<Item>() and exposes val items: List<Item> (often as a property that returns the private list, or a copy). Callers can read but not change; the class keeps control of its invariants. On Android you will see the same idea with a private mutable state holder and a public read-only one.

Mind the Java boundary. Kotlin's read-only List is a compile-time view. When you pass it to a Java method, Java sees an ordinary java.util.List and may call add on it. If the object really is an ArrayList, the change succeeds and your "read-only" list has changed. If you need a guarantee, pass a copy, or a list that refuses changes at run time (Java's List.copyOf).

Prefer the specific operation. The library usually has a function for exactly what you mean, and using it is clearer and often faster than composing general ones: any { } rather than filter { }.isNotEmpty(), count { } rather than filter { }.size, sumOf { } rather than map { }.sum(), firstOrNull { } rather than filter { }.firstOrNull(), associateBy rather than map { it.id to it }.toMap(). IntelliJ IDEA suggests many of these replacements automatically.

Maps have their own vocabulary. getOrElse(key) { default } and getOrPut(key) { compute() } (for mutable maps; perfect for caches and for building groups by hand), filterKeys, filterValues, mapValues, mapKeys, toSortedMap(), and +/- to make a new map with an entry added or removed. Iterate with for ((key, value) in map).

Arrays are for special cases. Kotlin has Array<T> and primitive arrays such as IntArray, and you need them for varargs, for some Java APIs and for performance-critical numeric code. Everywhere else, use lists: they have better equality (== on arrays compares identity, not contents), a readable toString, and the full collection API.

Common misconceptionsH

Common misconceptions

Misconception

"A List cannot change." A List reference cannot be used to change it, but if the same object is also reachable as a MutableList, changes made through that reference show up in the "read-only" view. Copy (toList()) when you need a snapshot.

Misconception

"Sequences are always faster." For small collections and short pipelines, eager list operations are usually faster, because they compile to simple loops. Sequences win when they avoid work or memory: early termination, huge data, infinite sources.

Misconception

"apply and also return the lambda's result." They return the object they were called on. let, run and with return the lambda's result.

Misconception

"associateBy groups elements." It keeps one element per key, the last one. Use groupBy to keep them all.

Exercises

Exercises

1. Collections, sequences and scope functions

Warm-upComputational

What does this program print?

fun main() {
    val fruit = listOf("apple", "avocado", "banana", "blueberry", "cherry")
    println(fruit.groupBy { it.first() }.mapValues { it.value.size })
}

2. Collections, sequences and scope functions

CoreComputational

What does this program print?

fun main() {
    var steps = 0
    val result = (1..10).asSequence().map { steps++; it * it }.filter { it > 20 }.take(2).toList()
    println("$result $steps")
}

3. Collections, sequences and scope functions

CoreComputational

What does this program print?

fun main() {
    val a = StringBuilder("x").apply { append("y") }.length
    val b = "kotlin".let { it.length * 2 }
    val c = listOf(1, 2).also { require(it.isNotEmpty()) }
    println("$a $b $c")
}

4. Collections, sequences and scope functions

CoreComputational

What does this program print?

fun main() {
    println(listOf(3, 1, 4, 1, 5).fold(0) { acc, x -> acc * 10 + x })
}

5. Collections, sequences and scope functions

Warm-upComputational

What does this program print?

fun main() {
    println(listOf("ant" to 1, "bee" to 2, "ant" to 3).toMap())
}

6. Collections, sequences and scope functions

StretchComputational

What does this program print?

fun main() {
    val backing = mutableListOf(1, 2)
    val view: List<Int> = backing
    backing.add(3)
    println(view)
}

7. Collections, sequences and scope functions

CoreHuman

In which situations is asSequence() likely to be the better choice than eager list operations? Choose all that apply.

Choose all that apply

Further reading and resources