📖 Scenario: You are working with a list of daily sales amounts in a small shop. You want to find the total sales and the highest single sale using Kotlin's fold and reduce operations.
🎯 Goal: Build a Kotlin program that uses fold to calculate the total sales and reduce to find the highest sale from a list of daily sales.
📋 What You'll Learn
Create a list of daily sales amounts with exact values
Create an initial value variable for fold operation
Use fold to calculate total sales
Use reduce to find the highest sale
Print the total sales and highest sale exactly as specified
💡 Why This Matters
🌍 Real World
Calculating total sales and highest sale is common in retail and business to understand performance.
💼 Career
Knowing fold and reduce helps in data processing tasks, common in software development and data analysis roles.
Progress0 / 4 steps
1
Create the sales data list
Create a list called dailySales with these exact values: 150, 200, 50, 400, 100
Kotlin
Hint
Use listOf to create the list with the exact numbers.
2
Create initial value for fold
Create an integer variable called initialTotal and set it to 0 to use as the starting value for the fold operation.
Kotlin
Hint
Just create a variable with the exact name and value.
3
Calculate total sales with fold and find highest sale with reduce
Use fold on dailySales with initialTotal to calculate the total sales and store it in totalSales. Then use reduce on dailySales to find the highest sale and store it in highestSale.
Kotlin
Hint
Use fold with an accumulator adding each sale, and reduce with a comparison to find the max.
4
Print the results
Print the total sales using println("Total sales: $totalSales") and print the highest sale using println("Highest sale: $highestSale").
Kotlin
Hint
Use println exactly as shown to print the results.
Practice
(1/5)
1. What is the main difference between fold and reduce in Kotlin?
easy
A. fold starts with an initial value; reduce starts with the first list item.
B. fold only works on numbers; reduce works on any type.
C. fold modifies the original list; reduce creates a new list.
D. fold is faster than reduce in all cases.
Solution
Step 1: Understand fold behavior
fold requires an initial value and then applies the operation starting from that value.
Step 2: Understand reduce behavior
reduce uses the first element of the list as the initial value and then applies the operation to the rest.
Final Answer:
fold starts with an initial value; reduce starts with the first list item. -> Option A
Quick Check:
fold initial value vs reduce first item = C [OK]
Hint: Remember: fold needs your start, reduce uses first item [OK]
Common Mistakes:
Thinking fold modifies the original list
Assuming reduce needs an initial value
Believing fold only works on numbers
2. Which of the following is the correct syntax to use fold on a list listOf(1, 2, 3) to sum all elements starting from 10?
easy
A. listOf(1, 2, 3).fold(10, (acc, item) -> acc + item)