Part 05 / Topic 8 of 8
Putting it together: a discount calculator
Every tool from this part, in one program: a checkout calculator for a shop ("Saral Mart") that
reads a variable number of item prices, totals them with a vararg function, works out a
membership discount through two overloaded functions (one by tier name, one by loyalty
years), applies an optional coupon, and adds GST -- all through default and named arguments, with
a local function doing the one validation only this calculation needs.
fun main() {
print("How many items are you billing? ")
val itemCount = readlnOrNull()?.trim()?.toIntOrNull() ?: 0
val prices = mutableListOf<Double>()
for (i in 1..itemCount) {
print("Item $i price: ₹")
val price = readlnOrNull()?.trim()?.toDoubleOrNull()
if (price == null || price < 0) {
println("Invalid price, treating item $i as ₹0.00")
prices.add(0.0)
} else {
prices.add(price)
}
}
val subtotalAmount = subtotal(*prices.toDoubleArray()) // spread: a List, collected at runtime, into a vararg call
print("Membership (regular/silver/gold, or number of loyalty years): ")
val membershipInput = readlnOrNull()?.trim() ?: "regular"
val discountPercent = if (membershipInput.isNotEmpty() && membershipInput.all { it.isDigit() }) {
membershipDiscountPercent(membershipInput.toInt()) // Int overload
} else {
membershipDiscountPercent(membershipInput.ifBlank { "regular" }) // String overload
}
print("Coupon discount percent (leave blank for none): ")
val couponPercent = readlnOrNull()?.trim()?.toDoubleOrNull() ?: 0.0
val total = finalBill(subtotalAmount, membershipDiscountPercent = discountPercent, couponPercent = couponPercent)
println()
println("Membership discount: %.1f%%".format(discountPercent))
println("Coupon discount: %.1f%%".format(couponPercent))
printReceiptLine("Subtotal", subtotalAmount)
printReceiptLine("Final amount (incl. GST)", total)
}
fun subtotal(vararg prices: Double): Double {
var total = 0.0
for (p in prices) total += p
return total
}
fun withGst(amount: Double): Double = amount * 1.18
// overload 1: membership named by tier
fun membershipDiscountPercent(tier: String): Double = when (tier.lowercase()) {
"gold" -> 15.0
"silver" -> 10.0
else -> 0.0
}
// overload 2: membership counted in years -- same name, resolved by argument type
fun membershipDiscountPercent(years: Int): Double = when {
years >= 5 -> 20.0
years >= 2 -> 10.0
years >= 1 -> 5.0
else -> 0.0
}
fun finalBill(
subtotal: Double,
membershipDiscountPercent: Double,
couponPercent: Double = 0.0,
applyGst: Boolean = true
): Double {
fun isValidPercent(p: Double) = p in 0.0..100.0 // local function
val safeCouponPercent = if (isValidPercent(couponPercent)) couponPercent else 0.0
val afterMembership = subtotal - subtotal * membershipDiscountPercent / 100
val afterCoupon = afterMembership - afterMembership * safeCouponPercent / 100
return if (applyGst) withGst(afterCoupon) else afterCoupon
}
fun printReceiptLine(label: String, amount: Double) {
println("%-28s ₹%10.2f".format(label, amount))
}
A few design choices worth noticing:
membershipDiscountPercentis overloaded by argument type, not just by name -- the caller decides which one runs simply by typing a tier name or a number of years;mainnever has to say which overload it means.finalBilltakes its membership percent as a named argument (membershipDiscountPercent = discountPercent) precisely because the function also has acouponPercentdefault and anapplyGstdefault sitting between the required parameter and that one -- naming it is what lets the call skip straight past both defaults cleanly.isValidPercentstays a local function insidefinalBillbecause nothing else in this program needs it; if a second function later needed the same check, that would be the moment to promote it to a top-level function (section 6's rule of thumb).withGstis a single-expression function -- one multiplication, no block body needed.
readlnOrNull() reads one line at a time, same as Part 4's ATM menu; every run below pipes the
whole conversation through printf so it's exactly reproducible:
$ kotlinc 08_discount_calculator.kt -include-runtime -d discount.jar
$ printf '3\n100\n250.50\n75\ngold\n\n' | java -jar discount.jar
How many items are you billing? Item 1 price: ₹Item 2 price: ₹Item 3 price: ₹Membership (regular/silver/gold, or number of loyalty years): Coupon discount percent (leave blank for none):
Membership discount: 15.0%
Coupon discount: 0.0%
Subtotal ₹ 425.50
Final amount (incl. GST) ₹ 426.78
A second run exercises the Int overload (7 years of loyalty) plus a coupon:
$ printf '2\n1000\n2000\n7\n10\n' | java -jar discount.jar
How many items are you billing? Item 1 price: ₹Item 2 price: ₹Membership (regular/silver/gold, or number of loyalty years): Coupon discount percent (leave blank for none):
Membership discount: 20.0%
Coupon discount: 10.0%
Subtotal ₹ 3000.00
Final amount (incl. GST) ₹ 2548.80
A third proves the invalid-price and blank-membership paths both fall back sensibly:
$ printf '2\nabc\n50\n\n\n' | java -jar discount.jar
How many items are you billing? Item 1 price: ₹Invalid price, treating item 1 as ₹0.00
Item 2 price: ₹Membership (regular/silver/gold, or number of loyalty years): Coupon discount percent (leave blank for none):
Membership discount: 0.0%
Coupon discount: 0.0%
Subtotal ₹ 50.00
Final amount (incl. GST) ₹ 59.00
Full program: examples/08_discount_calculator.kt.
Done here? The practice set for Part 5 — including the solutions — is on the part page.