Given a list of numbers, how do you compute its sum, average, and count in Kotlin, and how do you sum a numeric property of a list of objects?
answer
- sumOf return type follows the lambda type
- average() always Double, NaN when empty
- maxOrNull/minOrNull are the null-safe ones
- sumBy/sumByDouble removed → use sumOf
- count{} counts matches, count() = size
basics
~10 sUse sum() to add numbers, average() for the mean, count() for how many. To sum a field of objects, use sumOf { it.field }, which adds up the chosen value for each item.
solid answer
~40 sFor a List<Int>/List<Double> etc., sum() returns the total and average() returns a Double mean. count() returns the size (and count { predicate } counts matching elements). To total a property, use sumOf { it.price }; its return type follows the lambda — sumOf returning an Int lambda gives Int, a Long lambda gives Long, a Double lambda gives Double. The older sumBy/sumByDouble were deprecated/removed in favor of sumOf. For min/max use maxOrNull()/minOrNull() (nullable) or maxOf { }/minOf { } when you have a non-empty source or a selector. average() on an empty collection returns NaN, while sum() returns the additive identity (0).
code
kotlin · 9 linesval nums = listOf(1, 2, 3, 4)
println(nums.sum()) // 10
println(nums.average()) // 2.5
println(nums.count { it % 2 == 0 }) // 2
val empty = emptyList<Int>()
println(empty.sum()) // 0
println(empty.average()) // NaN
println(empty.maxOrNull()) // nullgo deeper
Knows sum/average/count exist and can sum a property with sumOf { }.
Recalls the empty-collection results (0, NaN, null) and that sumOf's type follows the lambda.
Explains why sumOf replaced sumBy and distinguishes maxByOrNull (element) from maxOfOrNull (value).
Discusses NaN propagation risks and chooses null-returning vs throwing variants intentionally in API design.
## What aggregation means Aggregation reduces a whole collection down to a single value: a total, a mean, a count. Kotlin's stdlib provides direct extension functions on `Iterable`, `Sequence`, `Array`, and primitive arrays. ## sum / sumOf - `sum()` works on collections of numeric types (`Int`, `Long`, `Double`, `Float`, etc.) and returns the same numeric type (with `Byte`/`Short` widening to `Int`). - `sumOf { selector }` maps each element to a number and totals them. The **return type is inferred from the lambda's type**: a lambda returning `Int` yields `Int`, returning `Long` yields `Long`, returning `Double` yields `Double`. This is how you sum a property: `orders.sumOf { it.amount }`. - `sumBy`/`sumByDouble` are the old names and are gone in modern Kotlin (2.x) — always use `sumOf`. ## average / count - `average()` always returns a `Double` regardless of input numeric type. - On an **empty** collection `average()` returns `Double.NaN`. - `count()` returns the element count as an `Int`. `count { predicate }` counts elements matching a predicate, e.g. `users.count { it.active }`. ## min / max - `maxOrNull()` / `minOrNull()` return the largest/smallest element or `null` if empty (so they are null-safe). - `maxByOrNull { selector }` / `minByOrNull { selector }` return the **element** whose selector value is largest/smallest. - `maxOfOrNull { selector }` / `minOfOrNull { selector }` return the **selector value** itself. - The non-`OrNull` variants (`maxOf`, `minOf`) throw `NoSuchElementException` on an empty source. ```kotlin data class Order(val id: Int, val amount: Double) val orders = listOf(Order(1, 10.0), Order(2, 5.5)) val total: Double = orders.sumOf { it.amount } // 15.5 val avg: Double = orders.map { it.amount }.average() // 7.75 val n: Int = orders.count() // 2 val pricey: Int = orders.count { it.amount > 6 } // 1 val biggest: Order? = orders.maxByOrNull { it.amount } // Order(1, 10.0) ``` ## Empty-collection edge cases (memorize) - `sum()` / `sumOf {}` → 0 (additive identity). - `average()` → `NaN`. - `maxOrNull()` / `minOrNull()` → `null`. - `count()` → 0.
- What does average() return for an empty list and why is that dangerous?Double.NaN. It's dangerous because NaN silently propagates through arithmetic and comparisons (NaN != NaN), so guard with isEmpty() or use a default.
- Why was sumBy replaced by sumOf?sumBy/sumByDouble had fixed return types and overload ambiguity; sumOf infers Int/Long/Double from the lambda, giving one consistent, type-correct API.
sumOf is like a cashier scanning each item and tallying the price you point to, not the item itself.
saying these in an interview costs you the question
- Claiming average() returns Int or throws on empty (it returns NaN)
- Using max()/min() and assuming non-null without checking emptiness
- Still recommending sumBy/sumByDouble
- Confusing sumOf (sums selector value) with count (counts elements)