August 2017
Intermediate to advanced
440 pages
10h
English
The sum function counts the sum of all elements in a list. It can be invoked on List<Int>, List<Long>, List<Short>, List<Double>, List<Float> , and List<Byte>:
val sum = listOf(1,2,3,4).sum()
println(sum) // Prints: 10
Often we need to sum some properties of elements, such as summing points of all users. It might be handled by mapping the list of users to the list of points and then counting the sum:
class User(val points: Int)
val users = listOf(User(10), User(1_000), User(10_000))
val points = users.map { it.points }. sum()
println(points) // Prints: 11010
But we unnecessarily create an intermediate collection by calling the map function, and it would be more efficient to directly sum points. ...
Read now
Unlock full access