Review this generated invoice code before it processes a large purchase list.
Calculate a discounted total in cents. Reject missing prices and negative quantities instead of silently accepting them.
kotlin
data class Purchase(
val priceCents: Long?,
val quantity: Int,
)
fun invoiceTotal(purchases: List<Purchase>, discountPercent: Int): Long {
var total = 0L
for (index in purchases.indices) {
val purchase = purchases.drop(index).first()
val price = purchase.priceCents!!
if (purchase.quantity < 0) continue
total += price * purchase.quantity
}
return total * (100 - discountPercent) / 100
}
fun customerMessage(name: String?, totalCents: Long): String {
val displayName = name ?: "Customer"
return "Hello $displayName, total: ${totalCents / 100}"
}
generated code is illustrative, not from any one model