Careeroza
Real World Example
A Food Delivery Cart
In a Zomato-style cart, some data never changes during the session (restaurant name, fees set by the app) and some changes on every tap (quantity, total). Choosing const, val and var correctly documents that intent.
Example
The cart total updates as the user adds items.
const val DELIVERY_FEE = 40
const val FREE_DELIVERY_ABOVE = 499
fun main() {
val restaurant = "Behrouz Biryani" // fixed for this cart
val itemPrice = 289 // fixed per item
var quantity = 1 // changes when user taps +
var total = itemPrice * quantity
println("$restaurant: $quantity item(s), subtotal ₹$total")
quantity += 1 // user taps +
total = itemPrice * quantity
val fee = if (total >= FREE_DELIVERY_ABOVE) 0 else DELIVERY_FEE
println("$restaurant: $quantity item(s), subtotal ₹$total, delivery ₹$fee")
println("Grand total: ₹${total + fee}")
}Output
Behrouz Biryani: 1 item(s), subtotal ₹289 Behrouz Biryani: 2 item(s), subtotal ₹578, delivery ₹0 Grand total: ₹578
Practice
Exercise: Create a constant MAX_PIN_ATTEMPTS = 3, a read-only bankName, and a mutable attemptsLeft. Decrease attemptsLeft once and print SBI: 2 attempts left.
Show answer
const val MAX_PIN_ATTEMPTS = 3
fun main() {
val bankName = "SBI"
var attemptsLeft = MAX_PIN_ATTEMPTS
attemptsLeft--
println("$bankName: $attemptsLeft attempts left")
}