Menu
Coddy logo textTech

Recap - Order Tracker

Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 36 of 57.

challenge icon

Challenge

Medium

Track orders with the special classes of this chapter.

  • The enum Status has the constants NEW, PAID, SHIPPED, DELIVERED and CANCELLED, each with a label (new, paid, ...), and canMoveTo(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 as NEW.
  • The sealed interface Outcome has the cases Updated(order) and Rejected(id, reason).
  • Tracker.place(item) creates an order with the next id (1, 2, ...) and returns it. move(id, target) returns Rejected with no such order or cannot go from new to delivered, or stores a changed copy of the order and returns Updated. summary() returns the number of orders per status in the enum's order, leaving out the statuses with none: paid 1, cancelled 1, or no orders.
  • describe(outcome) uses an exhaustive when and returns the updated order's text or rejected 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

Practice on your own: Kotlin playground