Careeroza
Real World Example
Order Status in a Food Delivery App
Swiggy and Zomato show an order moving through fixed stages. An enum holds the label, the progress bar value and the allowed next step.
Example
enum class OrderStatus(val label: String, val progress: Int) {
PLACED("Order placed", 10),
ACCEPTED("Restaurant accepted", 30),
PREPARING("Food is being prepared", 55),
OUT_FOR_DELIVERY("On the way", 80),
DELIVERED("Delivered", 100),
CANCELLED("Cancelled", 0);
val isActive get() = this != DELIVERED && this != CANCELLED
fun next(): OrderStatus = when (this) {
PLACED -> ACCEPTED
ACCEPTED -> PREPARING
PREPARING -> OUT_FOR_DELIVERY
OUT_FOR_DELIVERY -> DELIVERED
DELIVERED, CANCELLED -> this
}
}
fun progressBar(p: Int) = "[" + "#".repeat(p / 10) + "-".repeat(10 - p / 10) + "]"
fun main() {
var status = OrderStatus.PLACED
while (status.isActive) {
println("${progressBar(status.progress)} ${status.label}")
status = status.next()
}
println("${progressBar(status.progress)} ${status.label}")
}Output
[#---------] Order placed [###-------] Restaurant accepted [#####-----] Food is being prepared [########--] On the way [##########] Delivered
Storing Enums
- Save the enum
name(e.g."OUT_FOR_DELIVERY") in a database or API, not theordinal- reordering constants would corrupt stored ordinals. - Room stores enums with a
TypeConverter; kotlinx.serialization supports@SerialNameon constants.