MutableList
* sum()
The examples show you how to use sum() function to:
- sum of all items in the normal List
- sum of specific field in List of Objects (in need of map())
- sum of specific field of all values in a Map (in need of map())
Why we need map()?
map() will create a List of quantity first, then we invoke: List<quantity>.sum()
List
We’re gonna use sum() on List<Int> and List<Double> for example.
val nums = listOf(10, 20, 30) println(nums.sum()) // 60
val doubles = listOf(1.05, 2.05, 3.65) println(doubles.sum()) // 6.75
* sumBy()
The examples show you ways to use sumBy() function to:
- sum (and change value to Int) of all items in the normal List
- sum of specific Int field in List of Objects (no need map())
- sum of specific Int field of all values in Map of Objects (no need map())
Why we don’t need map()?
Look at protoype of sumBy() function:
inline fun sumBy(selector: (T) -> Int): Int
You can see that sumBy() receives a selector which indicates the field to be processed.
List
import kotlin.math.roundToInt val nums = listOf(10, 20, 30)
println(nums.sumBy { it }) // 60
println(nums.sumBy { it * 2 }) // 120
val doubles = listOf(1.05, 2.05, 3.65)
println(doubles.sumBy { it.roundToInt() }) // 7