Recap - Ticket Office
Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 16 of 57.
Challenge
MediumBuild a small ticket office from three kinds of declaration.
Tickethas a private constructor takingnumber,showandseat. Its companion holdsconst val SEATS = 3, a private counter and the factoryissue(show, seat), which gives tickets the numbers 1, 2, 3, ...;issuedis the number of tickets issued so far.label()returns#1 Hamlet seat 2.BoxOfficeis an object.sell(show, seat)repliesno seat 4when the seat is outside 1 toTicket.SEATS,seat 2 takenwhen it is sold for that show, and otherwise issues a ticket and replies with its label.refund(number)frees the seat of a sold ticket and repliesrefunded #1, orno ticket #9.report()repliesHamlet 2/3, Cats 1/3with the shows in alphabetical order, ornothing sold.
The supplied code reads commands sell Hamlet 2, refund 1 or report, prints each reply and finally tickets issued: with the count. Numbers are never reused after a refund.
Your code goes in Ticket.kt and BoxOffice.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()
for (cmd in input) {
val p = cmd.split(" ")
when (p[0]) {
"sell" -> println(BoxOffice.sell(p[1], p[2].toInt()))
"refund" -> println(BoxOffice.refund(p[1].toInt()))
else -> println(BoxOffice.report())
}
}
println("tickets issued: ${Ticket.issued}")
}
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 Books3Objects and Companions
Object DeclarationsCompanion ObjectsConstants With constObject ExpressionsRecap - Ticket OfficePractice on your own: Kotlin playground