List reduce in Kotlin

Level 3155 keystrokes

reduce combines the elements of a list into one value, from left to right: the first element is the starting accumulator. Here it computes the sum (15) and the product (120) of 1 to 5.

Kotlin code

// Create a read-only list of the numbers 1 to 5
1val nums = listOf(1, 2, 3, 4, 5)
// acc holds the result so far and n is the current element: ((((1+2)+3)+4)+5) = 15
2val sum = nums.reduce { acc, n -> acc + n }
// Same pattern with multiplication: 1*2*3*4*5 = 120 (reduce throws on an empty list)
3val product = nums.reduce { acc, n -> acc * n }
4
// Print 15
5println(sum)
// Print 120
6println(product)

Output

15
120
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • ,× 6
  • (× 3
  • )× 3
  • =× 3
  • -× 2
  • .× 2
  • {× 2
  • }× 2
  • >× 2
  • *× 1

More Kotlin examples at level 3

← Kotlin typing practice