Skip to workspace
Kotlin Lab

Everyday Kotlin / Chapter 02

Price a delivery with when

Put overlapping delivery rules in the order the business promises.

The decision

A shopper can qualify for free standard shipping and still choose express. Pickup overrides everything. Express costs 12. Standard delivery costs 5 below a subtotal of 50 and is free from 50.

Read the Kotlin

Read when from the top down

In a subjectless when, each left-hand side is a Boolean condition. The expression on the right of the first true condition becomes the result. Kotlin then leaves the whole expression. Trace an order that is both a pickup and express by covering every line below the first match.

val service = when {
    pickup -> "counter"
    express -> "courier"
    else -> "standard"
}

Test the intersection of two rules

To review a reorder, find an input that makes both moved conditions true. An express delivery over the free-shipping threshold qualifies for two different fees. Either rule alone gives the same answer before and after the edit. At the intersection, whichever rule comes first sets the price. A pickup still exits earlier.

Translate a two-way price

Kotlin’s if can produce a value, just like the Java conditional operator. Write the branch for a true condition first and give the false case after else. If you reverse the condition, exchange the two results too. Read both cases aloud before simplifying the expression.

val fare = if (hasPass) 2 else 6
val sameFare = if (!hasPass) 6 else 2

The full example

Java 25
class Lesson {
    static int deliveryFee(boolean pickup, boolean express, int subtotal) {
        if (pickup) return 0;
        if (express) return 12;
        return subtotal >= 50 ? 0 : 5;
    }
}
Kotlin/JVM
fun deliveryFee(pickup: Boolean, express: Boolean, subtotal: Int): Int =
    when {
        pickup -> 0
        express -> 12
        subtotal >= 50 -> 0
        else -> 5
    }

Inputs and outcomes

InputOutcomeWhy it matters
Delivery, standard, subtotal 495Standard charge still applies.
Delivery, express, subtotal 8012The express branch wins before the threshold.
Pickup, express, subtotal 800Pickup wins even with contradictory flags.

Walk through the code

  1. A subjectless when evaluates conditions in order. The first true branch supplies the value for the whole function. Java reaches the same decision with guard returns.
  2. Moving the threshold above express silently changes the price of large express orders. The order states a business rule.
  3. The final else gives the expression a result for the remaining combinations. A single two-way choice usually fits an if expression.

The Java habit

Translating separate assignments into independent if statements can let a later discount replace an earlier express charge.

When to choose differently

If many rules can apply together, an ordered when hides how fees combine. Calculate each additive component explicitly for that contract.

References

Open quizTry code