Recap - Payment Methods
Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 26 of 57.
Challenge
MediumDesign payment methods around an interface.
PaymentMethodrequiresname,fee(amount),pay(amount)(returns whether it paid) andstatus(), and gives a defaulttotal(amount): the amount plus the fee.Card(namecard) charges a 2% fee (rounded down), always pays and counts its payments:card: 2 payment(s).Wallet(balance)(namewallet) has no fee and pays only when the balance covers the total, which it then subtracts:wallet: 50 left.GiftCard(balance)(namegift card) has no fee either, but it only pays amounts of at most 100, and only when the balance covers them:gift card: 40 left.
Then complete checkout(amount, methods), which tries each PaymentMethod in order and returns paid 100 with wallet (total 100) for the first one that pays, or declined when none does.
The supplied code reads the methods as card,wallet:150,gift:120, then one amount per line, prints the result of each checkout and finally every method's status().
Your code goes in PaymentMethod.kt, Card.kt, Wallet.kt, GiftCard.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 methods = input[0].split(",").map { spec ->
val p = spec.split(":")
when (p[0]) {
"card" -> Card()
"wallet" -> Wallet(p[1].toInt())
else -> GiftCard(p[1].toInt())
}
}
for (line in input.drop(1)) println(checkout(line.toInt(), methods))
for (m in methods) println(m.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