Problem overview
A shop tracks how many pieces of each item it has: the item's stock. The stock can never go below 0, and it changes only when pieces are sold or new ones arrive. So the stock is a private property, changed only through two methods that check the rules. The item's name has no rules to protect, so it stays a property any code can read.
You write the class InventoryItem:
InventoryItem(name, initialStock)creates an item with that name and that many pieces.sell(n)sellsnpieces. Ifnis at least 1 and at most the stock, it lowers the stock bynand returnstrue. Otherwise it changes nothing and returnsfalse.restock(n)addsnpieces whennis at least 1 and ignoresnotherwise. It returns nothing.getStock()returns the stock, the only way for other code to read it.
For a pencil item with 5 in stock, sell(3) works and leaves 2. Selling 5 more is refused because only 2 are left, and restock(10) brings the stock to 12.
Approach: validate first, then change
Both methods follow the same pattern: check whether the request is valid, and only then change the state. A refused sale must leave the stock exactly as it was, so the check has to come before the subtraction. Doing it in this order means the stock can never go negative, whatever the caller passes in. That promise is possible only because the stock is private. If it were public, any code could write a negative number into it and bypass the checks.
Each method does a couple of comparisons and one addition or subtraction, so each runs in constant time.
Step by step
- The stock property. The header already has
val name, a public read-only property, and a plain parameterinitialStock. In the body, declareprivate var stock: Int = initialStock. It is avarbecausesellandrestockchange it, andprivateso that only they can. - Refuse bad sales. In
sell, anifjoins two conditions with||:n < 1(zero or negative pieces make no sale) orn > stock(the shop can't sell what it doesn't have). Its body returnsfalseand changes nothing. Note thatnequal to the stock is allowed: the shop may sell everything it has. - Do the sale. After the
if, only valid requests are left. Lowerstockbynand returntrue. - restock. An
ifforn >= 1addsnto the stock. Zero or a negative number isn't a delivery, so it is ignored, and there is noelse. - getStock returns
stock.
The solution in Kotlin
class InventoryItem(val name: String, initialStock: Int) {
private var stock: Int = initialStock
fun sell(n: Int): Boolean {
if (n < 1 || n > stock) {
return false
}
stock -= n
return true
}
fun restock(n: Int) {
if (n >= 1) {
stock += n
}
}
fun getStock(): Int {
return stock
}
}
Two Kotlin details to notice:
namehasvalin the header, so it is a public property;initialStockhas none, so it is only a constructor parameter. It exists while the property initializers run, and the privatestockcopies it. After that, onlystockis used.- The early
return falseinside theifends the method, so the lines after it run only for valid sales. A method with no return type, likerestock, returnsUnitautomatically.
Using the class
fun main() {
val p = InventoryItem("Pencil", 5)
println(p.name)
println(p.sell(3))
println(p.getStock())
println(p.sell(5))
println(p.getStock())
p.restock(10)
println(p.getStock())
p.restock(-5)
p.restock(0)
println(p.getStock())
println(p.sell(0))
println(p.sell(-3))
println(p.sell(12))
println(p.getStock())
}
It prints:
Pencil
true
2
false
2
12
12
false
false
true
0
Kotlin prints true and false; the lesson's tests print them as True and False. The sale of 5 with 2 in stock is refused and leaves 2, restocking 0 or -5 changes nothing, and selling exactly the 12 that are there empties the shelf.
Why return a Boolean from sell
A sale can fail for ordinary reasons, and the caller needs to know. Printing an error inside the class would decide for every caller how failure is reported. Returning true or false leaves that choice to the code that calls sell: it may show a message, try a smaller number or ignore the result. This is a common pattern for operations that may be refused: do nothing when the request is invalid, and say so in the return value.
restock has no such answer in this lesson. It silently ignores a bad amount, as the statement says, and returns nothing.
Testing it
- An item with stock 4:
sell(4)returnstrueand leaves 0, and thensell(1)returnsfalse. - An item with stock 0 at the start: every
sell(1)is refused until arestockarrives. - Two items with stock 10 each: after
sell(3)on the first, the first has 7 and the second still has 10, since each object has its own stock. - The limits in the constraints, -10000 and 10000, on an item with stock 7:
sell(-10000)andsell(10000)both returnfalse;restock(-10000)leaves the stock at 7, andrestock(10000)makes it 10007.
Common mistakes
- Refusing
n == stock. Writingn >= stockin the check blocks the sale of the last pieces. The test isn > stock. - Forgetting
n < 1. A sale of -3 would raise the stock, and a sale of 0 would report success for nothing. - Subtracting before checking. The stock must stay untouched when the answer is
false. - Using
&&instead of||. No number is both below 1 and above the stock, so the refusal would never happen. - Making
stockpublic. It would compile and pass simple tests, but outside code could set it to -4, which is exactly what the class is meant to prevent. - Letting
restockaccept negative numbers. That would act as a hidden sale with no checks.
