O'Reilly logo

Android Development with Kotlin by Igor Wojda, Marcin Moskala

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The sum, count, min, max, and sorted functions

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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required