Calculating totals
- Kotlin course
- Beginner
- Lesson 50/116
- 6 min
Learn to compute the subtotal and the tax-inclusive total.
Calculating totals (sumOf)
To sum the prices of all items, use sumOf. it represents each item in the list.
val total = cart.sumOf { it.price }
println(total) // 8.0Here it.price takes each item's price and adds them. With two items (5.0 + 3.0) the result is 8.0.
sumOf is a list function; it takes an expression in curly braces. it is Kotlin's automatic name; no loop variable needed. You'll see the details in the arrays topic.
Practice Calculate and print the total
Add val total = cart.sumOf { it.price } to the previous cart (two items). Print the total with println(total). The total should be 8.0.
Starter code
data class Product(val name: String, val price: Double)
fun main() {
val cart = mutableListOf<Product>()
cart.add(Product("Apple", 5.0))
cart.add(Product("Bread", 3.0))
// Calculate and print the total
}Sample solution
data class Product(val name: String, val price: Double)
fun main() {
val cart = mutableListOf<Product>()
cart.add(Product("Apple", 5.0))
cart.add(Product("Bread", 3.0))
val total = cart.sumOf { it.price }
println(total)
}Expected output
8.0
Tax calculation
For a tax-inclusive total, the tax rate is applied to the subtotal. For example 18% tax: val tax = total * 0.18.
val subtotal = cart.sumOf { it.price }
val tax = subtotal * 0.18
val grandTotal = subtotal + tax
println(grandTotal) // 9.44Here 8.0 + 1.44 = 9.44. The tax rate 0.18 (18%) is multiplied by the subtotal.
In this lesson we only calculate the subtotal; tax can be added later.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the sumOf call
val total = cart.____ { it.price }
val total = cart.sumOf { it.price }
Explanation: cart.sumOf { it.price } sums all prices.
2 What does cart.sumOf { it.price } do?
- Sums the prices Correct answer
- Gives the item count
- Takes the first item
- Empties the list
Explanation: sumOf { it.price } takes each item's price and adds them.
3 Match the total concepts
| Term | Meaning |
|---|---|
sumOf { it.price } |
Price sum |
it |
List item |
cart.size |
Item count |
total |
Subtotal |