Recap - Order Tracker
Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 36 of 57.
Challenge
MediumTrack orders with the special classes of this chapter.
- The enum
Statushas the constantsNEW,PAID,SHIPPED,DELIVEREDandCANCELLED, each with alabel(new,paid, ...), andcanMoveTo(next): new may become paid or cancelled, paid may become shipped or cancelled, shipped may become delivered, and nothing else is allowed. Order(id, item, status)is a data class whose status starts asNEW.- The sealed interface
Outcomehas the casesUpdated(order)andRejected(id, reason). Tracker.place(item)creates an order with the next id (1, 2, ...) and returns it.move(id, target)returnsRejectedwithno such orderorcannot go from new to delivered, or stores a changed copy of the order and returnsUpdated.summary()returns the number of orders per status in the enum's order, leaving out the statuses with none:paid 1, cancelled 1, orno orders.describe(outcome)uses an exhaustivewhenand returns the updated order's text orrejected 2: no such order.
The supplied code reads commands place tea or <status> <id> such as paid 1, prints each placed order, each described outcome and finally the summary.
Your code goes in Status.kt, Order.kt, Outcome.kt, Updated.kt, Rejected.kt, Tracker.kt and Functions.kt. Main.kt holds the supplied input/output code and cannot be edited.
Try it yourself
fun main() {
// Supplied input/output code: keep it as it is
val input = generateSequence(::readLine).toList()
val tracker = Tracker()
for (cmd in input) {
val p = cmd.split(" ")
if (p[0] == "place") {
println(tracker.place(p[1]))
} else {
val target = Status.entries.find { it.label == p[0] }
if (target == null) println("unknown status ${p[0]}")
else println(describe(tracker.move(p[1].toInt(), target)))
}
}
println(tracker.summary())
}
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesPrimary Constructorsinit Blocks and ValidationSecondary ConstructorsRecap - Library Card4Inheritance
Open Classes and SubclassesOverriding Memberssuper and ConstructorsAbstract ClassesRecap - Staff Directory7Special Classes
Data ClassesEnum ClassesSealed Hierarchiesequals, hashCode, toStringRecap - Order Tracker2Properties and Encapsulation
Custom AccessorsVisibility ModifiersPrivate Setterslazy and lateinitRecap - Bank Account5Interfaces
Declaring InterfacesDefault MethodsMultiple InterfacesInterfaces as TypesRecap - Payment Methods8Generics
Generic FunctionsGeneric ClassesType ConstraintsVariance With in and outRecap - Priority Queue11Project: Library Management
Books and MembersBorrowing BooksPractice on your own: Kotlin playground