0Pricing
Kotlin Academy · Lesson

Aggregation

sum, count, fold, reduce.

Aggregation is a free Kotlin Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Aggregating Collections

Aggregation reduces a collection to a single value. Kotlin provides ready-made functions like sum, count, average, max, and general-purpose fold and reduce.

sum and average

sum adds up numeric elements, and average returns their mean as a Double.

fun main() {
    val numbers = listOf(2, 4, 6, 8)
    println("Sum: ${numbers.sum()}")
    println("Average: ${numbers.average()}")
}

count

count returns the number of elements, optionally filtered by a predicate.

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6)
    println("Total: ${numbers.count()}")
    println("Even count: ${numbers.count { it % 2 == 0 }}")
}

maxOrNull and minOrNull

To find extremes safely, use maxOrNull and minOrNull, which return null for empty collections.

fun main() {
    val numbers = listOf(3, 7, 2, 9, 4)
    println("Max: ${numbers.maxOrNull()}")
    println("Min: ${numbers.minOrNull()}")
}

sumOf and maxByOrNull

sumOf sums a selected value per element, and maxByOrNull finds the element with the largest selected value.

data class Item(val name: String, val price: Int)

fun main() {
    val items = listOf(Item("a", 10), Item("b", 30), Item("c", 20))
    println("Total price: ${items.sumOf { it.price }}")
    println("Most expensive: ${items.maxByOrNull { it.price }?.name}")
}

The fold Function

fold combines elements into a single result, starting from an initial value. The lambda receives the running accumulator and the current element.

fun main() {
    val numbers = listOf(1, 2, 3, 4)
    val total = numbers.fold(100) { acc, n -> acc + n }
    println(total)
}

fold Can Change the Type

Because you provide the initial value, fold can build a result of any type, such as a String.

fun main() {
    val words = listOf("Kotlin", "is", "fun")
    val sentence = words.fold("") { acc, w -> if (acc.isEmpty()) w else "$acc $w" }
    println(sentence)
}

The reduce Function

reduce is like fold but uses the first element as the starting accumulator. It throws if the collection is empty and cannot change the type.

fun main() {
    val numbers = listOf(1, 2, 3, 4)
    val product = numbers.reduce { acc, n -> acc * n }
    println(product)
}

fold vs reduce

Key differences:

  • fold takes an initial value, works on empty collections, and can return a different type.
  • reduce starts from the first element, fails on empty collections, and keeps the element type.
fun main() {
    val empty = emptyList<Int>()
    println(empty.fold(0) { acc, n -> acc + n })
    println("fold is safe on empty lists")
}

runningFold and runningReduce

If you want every intermediate accumulator, runningFold (and runningReduce) returns the list of partial results.

fun main() {
    val numbers = listOf(1, 2, 3, 4)
    val sums = numbers.runningFold(0) { acc, n -> acc + n }
    println(sums)
}

Choosing an Aggregator

Use the specialized functions (sum, count, average, maxOrNull) when they fit. Reach for fold or reduce for custom combinations, preferring fold when an initial value or type change is needed.

Quick Check

What is the main difference between fold and reduce?

Recap

You learned to aggregate with sum, count, average, maxOrNull, sumOf, plus the general fold (initial value, any type, empty-safe) and reduce (first element seed). Next you will build maps and flatten nested collections.

Frequently asked questions

Is the “Aggregation” lesson free?

Yes — the full text of “Aggregation” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.

What will I learn in “Aggregation”?

sum, count, fold, reduce. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Kotlin Academy?

No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Aggregation” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Kotlin Academy lesson?

Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Filtering and Mapping
  2. Grouping and Partitioning
  3. Aggregation
  4. Association and Flattening
← Back to Kotlin Academy