Start learning free

LESSON 68 OF 70 · PROJECTS: OBJECT-ORIENTED

Vending Machine in Scala: A Class with Credit and Refunds

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.
  • def insert(amount: Double): Unit adds amount to the credit. Nothing is printed or returned.
  • def 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.
  • def 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 {
    def mainFunction(): Unit = {
        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

    def insert(amount: Double): Unit = {
        credit += amount
    }

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

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

STEP 1 OF 13
    Ctrl + Enter to check

    SCALA · PROJECTS: OBJECT-ORIENTED

    Vending Machine in Scala, explained

    Problem overview

    You build a VendingMachine class for a machine that sells one kind of item at a fixed price of 150. 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 machine is made with VendingMachine() and starts with credit 0.

    • insert(amount: Double): Unit adds amount to the credit. It prints and returns nothing.
    • select(): String tries to buy one item. If the credit is less than the price, it returns "Need N more", where N is the missing amount as a whole number, and the credit does not change. Otherwise it subtracts the price from the credit and returns "Dispensing!". Any extra money stays in the credit, and exact payment works.
    • refund(): Double returns the whole credit and sets it back to 0.

    In the driver, 50 is inserted and the machine answers Need 100 more. After another 150 the credit is 200, so it dispenses and keeps 50, and the refund is 50. Then 150 is an exact payment: it dispenses and the refund is 0. Finally 100 is short by 50, the credit stays 100, and the refund is 100:

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

    Approach: an object that remembers its state

    The credit has to survive between calls: insert changes it, and select and refund read it later. That is what a class is for. Each machine object has its own credit field, so two machines never share money. The field is a private var: private so that only the machine's own methods change it, and var because it changes over time.

    The key rule is in select. A failed purchase only reports what is missing and must not touch the credit. A successful one subtracts exactly the price, no more, so leftover money stays available for another purchase or a refund. The comparison is less than, which makes a credit equal to the price a success.

    Step by step

    1. Declare the class VendingMachine to hold the state and the actions on it.
    2. Add private var credit = 0.0. The literal 0.0 makes Scala infer the type Double, so no annotation is needed. A new machine holds no money.
    3. Add private var price = 150.0. Every item costs 150. It is a var in the lesson even though nothing changes it.
    4. Write the header of insert with a Double parameter amount and the result type Unit.
    5. Add amount to credit with +=. Add to what is already there; replacing it would lose earlier coins.
    6. Write the header of select, with no parameters and a String result.
    7. Handle too little money. If credit < price, return "Need " + (price - credit).toInt + " more". The toInt turns the missing amount into a whole number by dropping the decimals, so 100.0 prints as 100, not 100.0. The return sits inside the braces of a one-line if, and the credit is untouched.
    8. Subtract the price from the credit. Only a successful purchase reaches this line.
    9. Return "Dispensing!".
    10. Write the header of refund, with no parameters and a Double result.
    11. Save the credit in a val named r. Once the credit is reset, the old value would be gone.
    12. Reset credit to 0.0.
    13. Return r, the saved money.

    The solution in Scala

    class VendingMachine {
        private var credit = 0.0
        private var price = 150.0
    
        def insert(amount: Double): Unit = {
            credit += amount
        }
    
        def select(): String = {
            if (credit < price) { return "Need " + (price - credit).toInt + " more" }
            credit -= price
            return "Dispensing!"
        }
    
        def refund(): Double = {
            val r = credit
            credit = 0.0
            return r
        }
    }
    
    class Solution {
        def mainFunction(): Unit = {
            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)
        }
    }

    Scala details

    • Mixing a String and numbers with +. "Need " + (price - credit).toInt + " more" works because String's + converts the number to text. The parentheses make the subtraction happen first.
    • toInt truncates. It cuts off the fraction instead of rounding. With a credit of 100.5, the missing 49.5 becomes 49, so the message is Need 49 more. Without toInt, the message would read Need 49.5 more, and for whole amounts Need 100.0 more, which doesn't match the expected output.
    • Inferred types. private var credit = 0.0 has no written type, and Scala infers Double from the value. Writing 0 instead would infer Int and make the later += amount with a Double fail to compile.
    • return and result types. The methods that use return have their result types written, as Scala requires for them.
    • The driver's .toInt. refund() returns a Double, which would print as 50.0. The driver converts it to print 50.

    Edge cases and common mistakes

    • Exact payment. A credit of exactly 150 must dispense. Using credit <= price as the failure test would refuse it. The check is strictly less than.
    • Forgetting to subtract the price. The machine would dispense but keep the credit, and the refund would be too large. In the driver, the first refund would be 200 instead of 50.
    • Subtracting on a failed purchase. Subtract only after the check passes. A failed select must leave the credit exactly as it was.
    • Returning credit after resetting it. If refund sets credit = 0.0 and then returns credit, it always returns 0. The saved value r is what you return.
    • Asking for a refund twice. The second call returns 0, because the first one reset the credit.
    • Several purchases in a row. With 300 inserted, the first two select() calls dispense, and the third returns Need 150 more, since the credit is back to 0.

    Testing

    Try these on a new machine:

    • select() right away returns Need 150 more.
    • Insert 100.5, then select(): Need 49 more. refund() then returns 100.5, and a second refund() returns 0.0.
    • Insert 150 twice: two select() calls dispense, and the third returns Need 150 more.

    Key takeaways

    • A class keeps state in private fields that its methods read and change.
    • Check the failure case first, and change the state only on success.
    • Save a value in a local val before you reset the field you read it from.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free