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(): Stringtries 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(): Doublereturns 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:
insertalways changes it, by adding.selectchanges 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.refundhands 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
- Declare the class. It is a blueprint, and each machine has its own credit.
- Add
private var credit = 0.0. Writing0.0makes Kotlin inferDouble. It is avarbecause it changes. - Add
private var price = 150.0. Every item costs 150. - Start
insert, taking aDoublenamedamount. - Add the amount to
creditwith+=. It adds to what is there; it does not replace it. - Start
select, with no parameters and aStringresult. - Handle too little money. If
credit < price, return"Need ", then the missing amount(price - credit).toInt(), then" more". ThetoInt()call drops the decimals, so the message shows a whole number. The credit is not touched. - Charge for the item: subtract
pricefromcredit. - Return
"Dispensing!". This line runs only when the credit covered the price. - Start
refund, with no parameters and aDoubleresult. - Save the credit in
val r. Once the credit is reset, the old value would be gone. - Reset
creditto 0.0. - 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.0has no written type: the literal0.0is aDouble, so the property is one. Writing0would make it anInt, andcredit += amountwith aDoublewould then not compile. - Strings built with
+."Need " + (price - credit).toInt() + " more"joins a string, anIntand a string. Kotlin converts the number to text. The parentheses make the subtraction happen beforetoInt(). 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
ifare optional in Kotlin. The reference solution keeps them around thereturn. - Printing doubles.
refund()returns aDouble, which prints as50.0. The driver converts it withtoInt()to print50.
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
selectskipscredit -= 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, returningcreditwould always give 0. Return the savedr. - 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
selectboth dispense. The third answersNeed 150 more, and the credit is 0. - Fractions in the message. With 149.5 inserted,
selectanswersNeed 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.
