Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
82: List Operations: map, filter, fold In Depth
Imagine you're running a small warehouse. You have a giant conveyor belt carrying a mix of random items. Now, you don't want everything on that belt; you only want the electronics. Once you've picked those out, you want to put a protective foam wrap around each one. Finally, you want to know the total weight of all those wrapped electronics so you can book the right size shipping container.
That's exactly what filter, map, and fold do to your data. filter is your quality control—it keeps only what fits the criteria. map is your processing station—it changes every item in the list into something else. And fold is your final tally—it takes a whole list of things and collapses them down into one single value.
Sifting the Noise with Filter
I see a lot of developers write for loops with an if statement inside just to build a new list. Please, don't do that. It's noisy. In Kotlin, we use filter. It takes a predicate—basically a function that returns true or false—and returns a new list containing only the items that passed the test.
data class Product(val name: String, val price: Double, val category: String)
val inventory = listOf(
Product("Laptop", 1200.0, "Electronics"),
Product("Apple", 1.0, "Food"),
Product("Smartphone", 800.0, "Electronics"),
Product("Bread", 2.5, "Food")
)
// I only want the electronics
val electronics = inventory.filter { it.category == "Electronics" }
// Result: [Product(Laptop, 1200.0, Electronics), Product(Smartphone, 800.0, Electronics)]
Transforming the Results with Map
Once you have your filtered list, you often need to change the format of the data. Maybe you don't need the whole Product object anymore; maybe you just need a list of the prices to send to a payment gateway. That's where map comes in. It transforms every single element in the list using the logic you provide.
The key thing to remember here is that map can change the type of the list. We can go from a List<Product> to a List<Double> effortlessly.
// Now, let's just get the prices of those electronics
val prices = electronics.map { it.price }
// Result: [1200.0, 800.0]
Collapsing the List with Fold
This is where things get interesting. fold is the Swiss Army knife of list operations. While map and filter return another list, fold returns a single value. It does this by carrying an "accumulator" along as it traverses the list.
Think of it like a snowball rolling down a hill. You start with an initial value (the small snowball), and as it hits each element in the list, it adds to itself based on your logic.
// Let's calculate the total value of electronics, starting from 0.0
val totalValue = electronics.fold(0.0) { accumulator, product ->
accumulator + product.price
}
// Result: 2000.0
I'll be honest: fold can look intimidating at first because of the accumulator. But once you realize it's just a way to "reduce" a list into one result, it becomes your best friend. In the example above, 0.0 is the starting point. For the first product, accumulator is 0.0 and product.price is 1200.0. The result (1200.0) then becomes the accumulator for the next item.
Chaining it All Together
The real power happens when you chain these. Instead of creating intermediate variables like electronics and prices, you can pipe the data through a transformation pipeline. This is where Kotlin code starts to look really clean and expressive.
val grandTotal = inventory
.filter { it.category == "Electronics" }
.map { it.price * 1.10 } // Adding 10% tax to each item
.fold(0.0) { acc, price -> acc + price }
println("Total with tax: $grandTotal")
Just a heads-up: be mindful of performance on massive lists. Every time you call filter or map, Kotlin creates a new list in memory. If you're dealing with millions of items, look into asSequence() to make this "lazy," but for most day-to-day apps, chaining is the way to go.
📋 Practical Task
Exercise: The VIP Customer Revenue Calculator
You are building a reporting tool for a subscription service. You have a list of User objects. Your goal is to calculate the total revenue generated only from users who have a "Premium" status and have been members for more than 1 year.
The Requirements:
- Start with the provided list of users.
- Filter out anyone who is NOT "Premium".
- Filter out anyone whose
tenureYearsis 1 or less. - Map the remaining users to their
monthlyFee. - Use
foldto sum these fees into a total monthly revenue value.
data class User(val name: String, val status: String, val tenureYears: Int, val monthlyFee: Double)
val users = listOf(
User("Alice", "Premium", 2, 29.99),
User("Bob", "Free", 3, 0.0),
User("Charlie", "Premium", 1, 29.99),
User("Diana", "Premium", 5, 49.99),
User("Eve", "Free", 1, 0.0)
)
fun main() {
// Your code here:
// Chain filter, map, and fold to calculate the total revenue for eligible VIPs.
// Expected Result: 79.98 (Alice + Diana)
}
There are no comments for now.