Parking Garage
Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 55 of 57.
Challenge
HardBuild a parking garage.
- The enum
SizehasSMALL,MEDIUMandLARGE, in that order, each with a lower-caselabel. Vehicle(plate)is a sealed class with the abstract propertiessizeandhourlyRate.Motorbikeis small (1 per hour),Caris medium (3) andVanis 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 repliesparked AB12 in medium,full for AB12orAB12 is already parked.leave(plate, hours)frees the spot and repliesAB12 paid 9(rate times hours, at least 1 hour), orno vehicle AB12.status()repliesfree: 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
1Classes and Objects
Working With FilesDefining ClassesPrimary Constructorsinit Blocks and ValidationSecondary ConstructorsRecap - Library Card4Inheritance
Open Classes and SubclassesOverriding Memberssuper and ConstructorsAbstract ClassesRecap - Staff Directory2Properties 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