Careeroza
Real World Example
A Grocery Cart and Contacts
A quick-commerce app like Zepto or Blinkit keeps the menu as a read-only Map of prices, the cart as a MutableMap of item to quantity, and applied coupons as a MutableSet (a coupon cannot be applied twice). A chat app like WhatsApp keeps contacts in lists and finds common groups with set operations.
Example
Cart logic with all three collection types:
fun main() {
val catalog = mapOf("Milk 1L" to 66, "Bread" to 45, "Eggs (6)" to 54, "Bananas (1kg)" to 60)
val cart = mutableMapOf<String, Int>()
val coupons = mutableSetOf<String>()
fun addToCart(item: String, qty: Int = 1) {
if (item !in catalog) {
println("$item is not available")
return
}
cart[item] = (cart[item] ?: 0) + qty
}
addToCart("Milk 1L", 2)
addToCart("Bread")
addToCart("Eggs (6)")
addToCart("Bread")
addToCart("Ice Cream")
coupons.add("ZEPTO20")
coupons.add("ZEPTO20")
var subtotal = 0
for ((item, qty) in cart) {
val line = catalog.getValue(item) * qty
subtotal += line
println("${item.padEnd(10)} x$qty ₹$line")
}
val discount = if ("ZEPTO20" in coupons) subtotal * 20 / 100 else 0
println("Coupons: $coupons")
println("Subtotal ₹$subtotal, discount ₹$discount, pay ₹${subtotal - discount}")
val myGroups = setOf("Family", "College Friends", "Office")
val friendGroups = setOf("College Friends", "Cricket Team")
println("Groups in common: ${myGroups intersect friendGroups}")
}Output
Ice Cream is not available Milk 1L x2 ₹132 Bread x2 ₹90 Eggs (6) x1 ₹54 Coupons: [ZEPTO20] Subtotal ₹276, discount ₹55, pay ₹221 Groups in common: [College Friends]
Practice
Exercise: Create a mutableMapOf of student name to marks with three students. Add one more student, update one student's marks, then print each student as Name: marks and finally the class average.
Show answer
fun main() {
val marks = mutableMapOf("Asha" to 82, "Ravi" to 74, "Neha" to 91)
marks["Kiran"] = 68 // add
marks["Ravi"] = 79 // update
for ((name, m) in marks) println("$name: $m")
println("Average: ${marks.values.average()}") // 80.0
}