Start learning free

LESSON 68 OF 70 · PROJECTS: OBJECT-ORIENTED

Vending Machine in Kotlin: Credit, Select and Refund

Practice Read the full explanation

Build a VendingMachine class for a machine that sells one kind of item for a fixed price. It keeps the money inserted so far (the credit), sells an item when the credit is enough, and gives the remaining credit back on request. A new object is made with VendingMachine().

Rules:

  • State. A new machine has credit 0 and price 150 (every item costs 150). Declare private var credit = 0.0 and private var price = 150.0.
  • fun insert(amount: Double) adds amount to the credit. Nothing is printed or returned.
  • fun select(): String tries to buy one item and returns a string:
    • If the credit is less than the price, return "Need N more", where N is the missing amount (price - credit) as a whole number, for example "Need 100 more". The credit does not change.
    • Otherwise (the credit is equal to or greater than the price, so exact payment works), subtract the price from the credit and return "Dispensing!". Any extra money stays in the credit.
  • fun refund(): Double returns the whole credit and sets it back to 0, so asking again right away returns 0.

You start with this driver below your code:

class Solution {
    fun mainFunction() {
        val m = VendingMachine()
        m.insert(50.0)
        println(m.select())
        m.insert(150.0)
        println(m.select())
        println("Refunded: " + m.refund().toInt())
        m.insert(150.0)
        println(m.select())
        println("Refunded: " + m.refund().toInt())
        m.insert(100.0)
        println(m.select())
        println("Refunded: " + m.refund().toInt())
    }
}

Walk through it: 50 is not enough, so you see Need 100 more. After 150 more the credit is 200, so the machine dispenses and keeps 50 (200 - 150), and the refund is 50. Then 150 is exact payment: it dispenses and the refund is 0. Finally 100 is short by 50, the credit stays 100, and the refund is 100.

Expected output:

Need 100 more
Dispensing!
Refunded: 50
Dispensing!
Refunded: 0
Need 50 more
Refunded: 100

Convert the missing amount with (price - credit).toInt() so it prints as a whole number. Do the subtraction only when the item is dispensed, not when the credit is too low. If you forget it, the leftover credit is wrong and the refund is too big.

In the refund method, save the credit first, then reset it to 0, then return what you saved. Return the saved value, not credit.

class VendingMachine {
    private var credit = 0.0
    private var price = 150.0

    fun insert(amount: Double) {
        credit += amount
    }

    fun select(): String {
        if (credit < price) { return "Need " + (price - credit).toInt() + " more" }
        credit -= price
        return "Dispensing!"
    }

    fun refund(): Double {
        val r = credit
        credit = 0.0
        return r
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    KOTLIN · PROJECTS: OBJECT-ORIENTED

    Vending Machine in Kotlin, explained

    Problem overview

    The lesson asks for a VendingMachine class that sells one kind of item at a fixed price of 150. It remembers the money inserted so far, called the credit, and offers three actions:

    • insert(amount: Double) adds to the credit and returns nothing;
    • select(): String tries to buy one item. If the credit is below the price it returns "Need N more" and changes nothing. Otherwise it subtracts the price and returns "Dispensing!";
    • refund(): Double returns the whole credit and sets it back to 0.

    The driver inserts 50, so select answers that 100 more is needed. After 150 more the credit is 200, so the machine dispenses and keeps 50, and the refund is 50. Next, 150 is an exact payment, so the machine dispenses and the refund is 0. Last, 100 falls short by 50, and the refund is the 100 still in the machine:

    Need 100 more
    Dispensing!
    Refunded: 50
    Dispensing!
    Refunded: 0
    Need 50 more
    Refunded: 100
    

    Approach

    An object here is a small state machine. The state is two numbers, credit and price, and every method either reads the state, changes it, or both. Each machine made with VendingMachine() keeps its own credit.

    The key design question is what each method does to the credit:

    • insert always changes it, by adding.
    • select changes it only on a successful sale, by subtracting the price. A refused sale leaves it alone, so the customer can insert more and try again.
    • refund hands it all back and resets it.

    Keeping the leftover credit after a sale, instead of ejecting change right away, is what lets 200 pay for one item and still leave 50 to refund.

    Step by step

    1. Declare the class. It is a blueprint, and each machine has its own credit.
    2. Add private var credit = 0.0. Writing 0.0 makes Kotlin infer Double. It is a var because it changes.
    3. Add private var price = 150.0. Every item costs 150.
    4. Start insert, taking a Double named amount.
    5. Add the amount to credit with +=. It adds to what is there; it does not replace it.
    6. Start select, with no parameters and a String result.
    7. Handle too little money. If credit < price, return "Need ", then the missing amount (price - credit).toInt(), then " more". The toInt() call drops the decimals, so the message shows a whole number. The credit is not touched.
    8. Charge for the item: subtract price from credit.
    9. Return "Dispensing!". This line runs only when the credit covered the price.
    10. Start refund, with no parameters and a Double result.
    11. Save the credit in val r. Once the credit is reset, the old value would be gone.
    12. Reset credit to 0.0.
    13. Return r, the saved amount.

    The solution in Kotlin

    class VendingMachine {
        private var credit = 0.0
        private var price = 150.0
    
        fun insert(amount: Double) {
            credit += amount
        }
    
        fun select(): String {
            if (credit < price) { return "Need " + (price - credit).toInt() + " more" }
            credit -= price
            return "Dispensing!"
        }
    
        fun refund(): Double {
            val r = credit
            credit = 0.0
            return r
        }
    }
    
    class Solution {
        fun mainFunction() {
            val m = VendingMachine()
            m.insert(50.0)
            println(m.select())
            m.insert(150.0)
            println(m.select())
            println("Refunded: " + m.refund().toInt())
            m.insert(150.0)
            println(m.select())
            println("Refunded: " + m.refund().toInt())
            m.insert(100.0)
            println(m.select())
            println("Refunded: " + m.refund().toInt())
        }
    }
    

    Kotlin details

    • Type inference. private var credit = 0.0 has no written type: the literal 0.0 is a Double, so the property is one. Writing 0 would make it an Int, and credit += amount with a Double would then not compile.
    • Strings built with +. "Need " + (price - credit).toInt() + " more" joins a string, an Int and a string. Kotlin converts the number to text. The parentheses make the subtraction happen before toInt().
    • toInt() truncates. It drops the fraction, it does not round: 149.5.toInt() is 149, and a missing 0.5 becomes 0.
    • The braces on a one-line if are optional in Kotlin. The reference solution keeps them around the return.
    • Printing doubles. refund() returns a Double, which prints as 50.0. The driver converts it with toInt() to print 50.

    Edge cases and common mistakes

    • Exact payment. The test is credit < price, so a credit of exactly 150 passes and dispenses. Writing <= would refuse exact payment.
    • Forgetting to subtract. If select skips credit -= price, the machine dispenses for free forever, and the refund after the second sale would be 200, not 50.
    • Subtracting on a refusal. The subtraction belongs below the guard. Done before it, a short payment would push the credit below zero.
    • Refund returning the wrong thing. After credit = 0.0, returning credit would always give 0. Return the saved r.
    • Asking again. A second refund() straight away returns 0.0, because the first one reset the credit.
    • Several items from one payment. With 300 inserted, the first two calls to select both dispense. The third answers Need 150 more, and the credit is 0.
    • Fractions in the message. With 149.5 inserted, select answers Need 0 more, because the missing 0.5 is cut to 0. The lesson's driver uses whole numbers, so the tests never hit this.

    Testing

    Try inserting 300 and calling select three times: the answers are Dispensing!, Dispensing! and then Need 150 more, and a refund afterwards is 0.0. Try a machine with nothing inserted, too. select answers Need 150 more and refund returns 0.0, so a refund with nothing to give back is harmless.

    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free