Menu
Coddy logo textTech

Recap - Payment Methods

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

challenge icon

Challenge

Medium

Design payment methods around an interface.

  • PaymentMethod requires name, fee(amount), pay(amount) (returns whether it paid) and status(), and gives a default total(amount): the amount plus the fee.
  • Card (name card) charges a 2% fee (rounded down), always pays and counts its payments: card: 2 payment(s).
  • Wallet(balance) (name wallet) has no fee and pays only when the balance covers the total, which it then subtracts: wallet: 50 left.
  • GiftCard(balance) (name gift 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

Practice on your own: Kotlin playground