在这段生成的发票代码处理大型购买列表前审查它。
计算折扣后的总金额(单位为分)。价格缺失或数量为负时应拒绝数据,不能静默接受。
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}"
}
生成代码仅作示例,不代表任何特定模型