Menu
Coddy logo textTech

Parking Garage

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

challenge icon

Challenge

Hard

Build a parking garage.

  • The enum Size has SMALL, MEDIUM and LARGE, in that order, each with a lower-case label.
  • Vehicle(plate) is a sealed class with the abstract properties size and hourlyRate. Motorbike is small (1 per hour), Car is medium (3) and Van is large (5).
  • Garage(small, medium, large) is created with the number of spots per size. park(vehicle) puts the vehicle in a free spot of its own size or, if there is none, of the next larger size that has one, and replies parked AB12 in medium, full for AB12 or AB12 is already parked. leave(plate, hours) frees the spot and replies AB12 paid 9 (rate times hours, at least 1 hour), or no vehicle AB12. status() replies free: small 1, medium 0, large 2.

The supplied code reads the spots as small,medium,large, then commands park car AB12 (bike, car or van), leave AB12 3 or status, and prints each reply.

Your code goes in Size.kt, Vehicle.kt, Motorbike.kt, Car.kt, Van.kt and Garage.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 (small, medium, large) = input[0].split(",").map { it.toInt() }
    val garage = Garage(small, medium, large)
    for (cmd in input.drop(1)) {
        val p = cmd.split(" ")
        when (p[0]) {
            "park" -> {
                val vehicle = when (p[1]) {
                    "bike" -> Motorbike(p[2])
                    "van" -> Van(p[2])
                    else -> Car(p[2])
                }
                println(garage.park(vehicle))
            }
            "leave" -> println(garage.leave(p[1], p[2].toInt()))
            else -> println(garage.status())
        }
    }
}

All lessons in Object Oriented Programming

Practice on your own: Kotlin playground