The Analogy: The Dye House and the One Recipe Card
In a woollen dye house the vats stand in a row and every batch of fibre that goes into one needs a measured weight of mordant, the salt that makes the dye bite. The weight is not a matter of taste. It follows from the fibre: wool takes a heavy dose, silk a light one, flax something in between. So a decision has to be made for every batch, and there are two quite different ways to organise the shop around it, which look equally sensible from the door and behave very differently by Friday.
The first way puts the decision in the hands of whoever is at the vat. A hand looks at the docket, sees wool, walks to the wool bin and ladles in the heavy dose; another hand sees silk and ladles the light one. Nobody writes anything down. The decision and the act are the same event, performed at the vat, and the shop works perfectly well as long as the hands know the three fibres and nothing else ever arrives.
The second way separates deciding from doing. The foreman reads the docket, works out the one figure that applies, and writes it in the single box on a recipe card: 1440 grams, and nothing else. The card then goes to the vat, and the hand at the vat does not think about fibre at all -- it weighs out what the card says. One figure, written once, in a place where anyone can see it. If the foreman is asked afterwards what went into vat three, the answer is on the card rather than in somebody's memory.
The failure mode is what separates the two, and it only shows up when a fourth fibre arrives. Under the first arrangement the hand looks at the docket, sees a word it does not know, checks the wool bin and the silk bin and the flax bin, finds no instruction that fits, and does the only thing available: nothing. No mordant goes in. Nobody is told, because not-ladling makes no noise, and the fault surfaces three days later as streaky cloth on the finishing table with no record of what caused it. Under the second arrangement the foreman reaches the end of the rule and has no figure to write, so the box on the card stays empty -- and an empty box stops the vat immediately, because a hand cannot weigh out nothing. That is exactly the difference between if used as a statement and if used as an expression in Kotlin. A statement if with no else may quietly do nothing. An expression if must produce a value, so the compiler refuses to let you write one without an else.
Syntax or Core Structure
An if in Kotlin is not a statement that happens to be usable in one place; it is an expression everywhere, and using it as a statement is simply throwing its value away. Write if (c) a else b and the whole thing evaluates to a or to b, which is why Kotlin has no ternary operator -- there would be nothing for it to do. Give each branch braces and the value becomes the last expression inside the chosen block. The only rule to remember is that a value must exist on every path, so the moment you assign or return an if, the else stops being optional.
fun mordantGrams(fibre: String, kg: Int): Int =
if (fibre == "WOOL") kg * 120
else if (fibre == "SILK") kg * 45
else kg * 80
fun main() {
val kg = 12
val fibre = "SILK"
val grams = if (fibre == "WOOL") kg * 120 else kg * 45
println("grams: " + grams)
val vatLitres = if (kg > 10) {
val base = 40
base + kg * 2
} else {
20 + kg
}
println("vat litres: " + vatLitres)
var warnings = 0
if (kg > 10) warnings++
println("warnings: " + warnings)
println("wool 12 kg: " + mordantGrams("WOOL", 12))
println("silk 12 kg: " + mordantGrams("SILK", 12))
println("flax 12 kg: " + mordantGrams("FLAX", 12))
val note: Any = if (kg > 10) kg else "small batch"
println("note: " + note)
}
Output:
grams: 540
vat litres: 64
warnings: 1
wool 12 kg: 1440
silk 12 kg: 540
flax 12 kg: 960
note: 12
Four different jobs in one screen. grams is the plain expression form: the condition is false, so the else branch gives 12 times 45, and 540 is written into a val that can never afterwards be reassigned or left unset. vatLitres shows the block form -- the chosen block declares a local base and then ends in base + kg * 2, and it is that final expression, 40 plus 24, that becomes the value; the val base = 40 line contributes nothing to the result and would be a mistake to put last. warnings is the statement form, with no else and no value: the if runs warnings++ for its side effect and evaluates to Unit, which is discarded. mordantGrams is an else if chain used as the whole body of a function, and note shows what happens when the branches disagree about type -- an Int and a String have no common numeric type, so the declared type has to be Any, and 12 is printed through Any.toString.
Technical Depth: The Value, the Type and the Compulsory else
Everything about if follows from one fact: it evaluates to something. Whether you are obliged to supply an else depends entirely on whether that something is used, and the type of the result is decided by the branches rather than by you.
| Form | Written as | Is else required | What it evaluates to |
|---|---|---|---|
| statement, no else | if (c) doThing() | no | Unit, discarded |
| statement with else | if (c) a() else b() | no | Unit, discarded |
| assigned to a name | val x = if (c) p else q | yes | the chosen branch's value |
| returned | return if (c) p else q | yes | the chosen branch's value |
| expression body | fun f() = if (c) p else q | yes | the chosen branch's value |
| passed as an argument | log(if (c) p else q) | yes | the chosen branch's value |
| branches in braces | braces around either branch | yes when the value is used | the last expression in the chosen block |
The type of the whole if is the least common supertype of its branches, computed by the compiler and not negotiable. That is worth dwelling on, because it is the one place where if surprises people arriving from C or Java, both of which will happily widen an int to a long across a conditional.
| Branch types | Type of the whole if | What that means in practice |
|---|---|---|
both Int | Int | no boxing and no conversion |
an Int branch and a Long branch | a common supertype, not Long | Kotlin never widens across branches; convert inside the branch |
a String branch and a null branch | String? | the ordinary way to build a nullable value |
a String branch and an Int branch | Any | usually a sign the branches answer different questions |
a value branch and a throw branch | the value branch's type | Nothing is a subtype of every type |
a value branch and a return branch | the value branch's type | the same rule; the branch never completes |
both branches Unit | Unit | the statement case wearing expression clothes |
The two rows about Nothing are the useful ones. throw and return are expressions of type Nothing, the type with no values, and Nothing sits below everything in the hierarchy. So val n = if (ok) count else throw IllegalStateException("no count") has type Int, not Any: the compiler knows the throwing branch cannot produce a value, so the only type it has to account for is the other one. That is what lets you refuse a case in an expression without inventing a sentinel like -1 and hoping every caller remembers it.
An else if chain, a when, and the value of a block
An else if chain and a subject-less when compile to the same sequence of tests, and for three or four numeric bands they are equally correct; the choice is about how the code reads. A braced branch, meanwhile, is not a list of statements with a return somewhere in it -- it is a block whose value is whatever its final expression evaluates to, and everything above that line exists only to prepare it. Get the order wrong and the block still compiles; it just hands back the wrong thing, or Unit.
fun gradeIf(strength: Int): String =
if (strength >= 90) "PRIME"
else if (strength >= 70) "GOOD"
else if (strength >= 50) "FAIR"
else "REJECT"
fun gradeWhen(strength: Int): String = when {
strength >= 90 -> "PRIME"
strength >= 70 -> "GOOD"
strength >= 50 -> "FAIR"
else -> "REJECT"
}
fun main() {
val samples = listOf(94, 88, 70, 51, 12)
var agreed = 0
for (s in samples) {
val a = gradeIf(s)
val b = gradeWhen(s)
if (a == b) agreed++
println("strength " + s + ": if=" + a + " when=" + b)
}
println("agreed on " + agreed + " of " + samples.size)
val trimmed = if (samples.size > 3) {
val head = samples.take(3)
head.sum()
} else {
samples.sum()
}
println("sum of the first three: " + trimmed)
}
Output:
strength 94: if=PRIME when=PRIME
strength 88: if=GOOD when=GOOD
strength 70: if=GOOD when=GOOD
strength 51: if=FAIR when=FAIR
strength 12: if=REJECT when=REJECT
agreed on 5 of 5
sum of the first three: 252
The five grades agree because the two functions test the same thresholds in the same order, and the count on the sixth line says so rather than leaving you to read five pairs and trust your eyes. Notice 70: it fails >= 90 and passes >= 70, so both forms stop at the second test, and neither the chain nor the when needs the branches to be mutually exclusive -- they need only be in the right order. The trimmed block at the end is the last-expression rule in miniature: val head = samples.take(3) is a declaration and contributes no value, so the block's value is head.sum(), which is 94 plus 88 plus 70. Move head.sum() above the declaration and the code no longer compiles; leave a println as the final line instead and it compiles but the block's value becomes Unit.
Smart casts, and the else you cannot omit
Because if is an expression, a null check written as an if does two things at once: it chooses a branch and it narrows the type inside that branch. The compiler tracks what the condition proved, so in the branch where a String? is known not to be null it is a String, with no cast written anywhere.
class Batch(val fibre: String, val kg: Int)
fun mordantFor(b: Batch): Int {
val perKg = if (b.fibre == "WOOL") 120
else if (b.fibre == "SILK") 45
else if (b.fibre == "FLAX") 80
else throw IllegalArgumentException("unpriced fibre " + b.fibre)
return perKg * b.kg
}
fun labelFor(b: Batch?): String =
if (b == null) "no batch on the bench"
else "batch of " + b.kg + " kg " + b.fibre
fun main() {
val bench = listOf(Batch("WOOL", 12), Batch("FLAX", 5), Batch("SILK", 3))
var total = 0
for (b in bench) {
val g = mordantFor(b)
total += g
println(labelFor(b) + " needs " + g + " g")
}
println(labelFor(null))
println("total mordant: " + total + " g")
val declared = 3
val counted = bench.size
val verdict = if (declared == counted) "bench agrees"
else "bench differs by " + (counted - declared)
println(verdict)
}
Output:
batch of 12 kg WOOL needs 1440 g
batch of 5 kg FLAX needs 400 g
batch of 3 kg SILK needs 135 g
no batch on the bench
total mordant: 1975 g
bench agrees
Three things are worth pulling out. perKg has type Int even though one of its four branches is a throw, because throw has type Nothing and Nothing is a subtype of Int; the alternative -- returning -1 for an unknown fibre and multiplying it by the weight -- would have produced a negative mordant figure and printed it without complaint. In labelFor the parameter is Batch?, and the else branch reads b.kg and b.fibre with no !! and no cast, because the if (b == null) on the line above proved what the compiler needed; that narrowing is only available because the check and the use are in the same expression. And verdict is the pattern to reach for whenever two numbers ought to match: one val, both branches producing a String, and the disagreeing branch carrying the size of the disagreement rather than just the word "no".
Real World Example: Costing a Day's Dye Vats
Six vats were charged this morning and the office wants a costing sheet. Each vat needs a mordant figure from the fibre, a dye figure from the shade, a size band printed on the sheet so the warehouse can see at a glance which batches were bulk, and a discount in pence. Four decisions, every one of them a two-or-three-way choice on a single value, which is exactly the shape if fits; the program assigns each one to a val and prints the sheet as a fixed-width board so every column can be added up and checked.
const val BATCHES = "WOOL:12:DEEP,SILK:3:PALE,FLAX:5:DEEP,WOOL:10:MID,FLAX:9:MID,SILK:1:PALE"
const val W_FIBRE = 7
const val W_KG = 4
const val W_SHADE = 6
const val W_MORD = 7
const val W_DYE = 7
const val W_BAND = 6
const val W_DISC = 6
const val W_NET = 7
val BANDS = listOf("BULK", "PART", "NONE")
fun mordantPerKg(fibre: String): Int =
if (fibre == "WOOL") 120
else if (fibre == "SILK") 45
else if (fibre == "FLAX") 80
else throw IllegalArgumentException("unpriced fibre " + fibre)
fun dyePerKg(shade: String): Int =
if (shade == "DEEP") 90
else if (shade == "MID") 55
else 30
fun bandFor(kg: Int): String =
if (kg >= 10) "BULK" else if (kg >= 5) "PART" else "NONE"
fun discountFor(kg: Int): Int =
if (kg > 10) 200 else if (kg >= 5) 60 else 0
fun row(fibre: String, kg: String, shade: String, mord: String,
dye: String, band: String, disc: String, net: String): String =
fibre.padStart(W_FIBRE) + kg.padStart(W_KG) + shade.padStart(W_SHADE) +
mord.padStart(W_MORD) + dye.padStart(W_DYE) + band.padStart(W_BAND) +
disc.padStart(W_DISC) + net.padStart(W_NET)
fun main() {
val width = W_FIBRE + W_KG + W_SHADE + W_MORD + W_DYE + W_BAND + W_DISC + W_NET
val records = BATCHES.split(",")
val tally = IntArray(BANDS.size)
var totalKg = 0
var totalMord = 0
var totalDye = 0
var totalDisc = 0
var totalNet = 0
println(row("FIBRE", "KG", "SHADE", "MORD", "DYE", "BAND", "DISC", "NET"))
println("-".repeat(width))
for (record in records) {
val parts = record.split(":")
val fibre = parts[0]
val kg = parts[1].toInt()
val shade = parts[2]
val mord = mordantPerKg(fibre) * kg
val dye = dyePerKg(shade) * kg
val band = bandFor(kg)
val disc = discountFor(kg)
val net = mord + dye - disc
tally[BANDS.indexOf(band)]++
totalKg += kg
totalMord += mord
totalDye += dye
totalDisc += disc
totalNet += net
println(row(fibre, kg.toString(), shade, mord.toString(),
dye.toString(), band, disc.toString(), net.toString()))
}
println("-".repeat(width))
println(row("TOTALS", totalKg.toString(), "--", totalMord.toString(),
totalDye.toString(), "--", totalDisc.toString(), totalNet.toString()))
println("bands: " + BANDS.mapIndexed { i, b -> b + "=" + tally[i] }.joinToString(" "))
println("vats: " + records.size + " total kg: " + totalKg)
println("sum of net column: " + totalNet)
println("mord " + totalMord + " + dye " + totalDye + " - disc " + totalDisc +
" = " + (totalMord + totalDye - totalDisc) +
" agree: " + (totalNet == totalMord + totalDye - totalDisc))
}
Output:
FIBRE KG SHADE MORD DYE BAND DISC NET
--------------------------------------------------
WOOL 12 DEEP 1440 1080 BULK 200 2320
SILK 3 PALE 135 90 NONE 0 225
FLAX 5 DEEP 400 450 PART 60 790
WOOL 10 MID 1200 550 BULK 60 1690
FLAX 9 MID 720 495 PART 60 1155
SILK 1 PALE 45 30 NONE 0 75
--------------------------------------------------
TOTALS 40 -- 3940 2695 -- 380 6255
bands: BULK=2 PART=2 NONE=2
vats: 6 total kg: 40
sum of net column: 6255
mord 3940 + dye 2695 - disc 380 = 6255 agree: true
Follow the third vat. Five kilograms of flax: mordantPerKg fails the wool test and the silk test, passes the flax test and returns 80, so the mordant is 400 grams; dyePerKg passes its first test on "DEEP" and returns 90, so the dye is 450; bandFor fails kg >= 10 and passes kg >= 5, giving "PART"; and discountFor fails kg > 10 and passes kg >= 5, giving 60. Net is 400 plus 450 minus 60, the 790 in the last column. Every one of those four values arrives in a val initialised by an if, so there is no moment in the loop at which any of them is declared but not yet decided.
The audit lines at the foot exist to be checked rather than read. The band tally is an IntArray indexed by position in BANDS, not a hash map, so BULK=2 PART=2 NONE=2 appears in declared order on every run and every platform, and the three counts sum to the six vats on the line below. The kilogram total is printed in the KG column of the totals row and again in words, so a mis-parsed record would show up as two different numbers rather than one plausible one. And the last line recomputes the net total from the three other column totals, independently of the running sum, and prints whether they agree -- one println that turns a forgotten accumulator or a double-counted discount into a visible false.
Now look at the fourth vat, and at the difference between what the sheet says and what the office charged. Ten kilograms of wool is labelled BULK, because bandFor tests kg >= 10, but its discount is 60, because discountFor tests kg > 10. Every other BULK line on the board carries 200. That is the design flaw, and it is not a rough edge: the same business decision -- is this batch a bulk batch -- has been written twice, in two functions, with two thresholds, and the two disagree on exactly one value. Nothing in the output announces it. The columns add up, the reconciliation line says true, and the sheet is internally consistent while charging a bulk customer the part-load rate; the only way to see it is to notice that a row reading BULK and 60 is impossible. The fix is structural rather than a corrected comparison: have bandFor be the single place the question is answered and let discountFor take the band rather than the weight, so there is one threshold in the program and the two columns cannot drift apart again. Two smaller limits alongside it: dyePerKg ends in a bare else 30 that prices an unknown shade as "PALE" instead of refusing it, unlike mordantPerKg, which throws; and row pads but never truncates, so a fibre name over seven characters would silently push every column to its right.
Common Mistakes
- Leaving
elseout of anifthat has to produce a value. The compiler stops you, and the instinct is to add a placeholder such aselse 0orelse ""to make the error go away. That placeholder is a decision you have not made. If there is genuinely no sensible value, put athrowor areturnin the branch and let itsNothingtype keep the result type honest.
- Declaring a
varand filling it from a statementif. Two lines instead of one, a name that is mutable for the rest of the function, and no guarantee that every path assigns it. Writeval x = if (c) p else qand the compiler enforces exactly one assignment on exactly one path.
- Ending a block branch with something that is not the value you meant. The value of a braced branch is its last expression. A trailing
printlnmakes the branchUnit, and a trailing assignment does the same, so the wholeifcollapses toUnitand the interesting number computed two lines earlier is thrown away.
- Expecting numeric widening across branches.
if (c) 1 else 2Ldoes not give you aLong; the branches keep their own types and the result is a common supertype you cannot do arithmetic on. Convert inside the branch, as inif (c) 1L else 2L.
- Testing a
Boolean?as though it were aBoolean. A nullable boolean cannot be a condition, because there is no branch for null. Writeif (flag == true)when absence should behave as false, and handle the three cases separately when it should not.
- Using an
else ifchain over a closed set of values. An enum or a sealed hierarchy gets an exhaustiveness check fromwhen; a chain ofelse ifgets none, so adding a fourth case leaves the finalelsequietly absorbing it and the compiler says nothing.
- Mixing a side effect into one branch of an expression
if. If one branch computes a value and the other logs and returns a default, theifis doing two jobs and only one of them is visible at the call site. Split the guard out and let theifproduce a value only.
- Reaching for a ternary operator. Kotlin has none, and adding a helper function or extra parentheses to simulate one is wasted effort, because
ifalready is the ternary.val n = if (c) a else bis the idiom; wrapping it in parentheses only adds noise.
- Letting the condition do the work twice.
if (readings.first() > 0) readings.first() else 0evaluatesfirst()twice, which costs time on a sequence and can give two different answers on anything mutable. Bind it once and test the name.
Best Practices
- Prefer the expression form everywhere it fits. Assign or return the whole
ifrather than assigning inside its branches, and the compiler starts checking that every path produces exactly one value.
- Let
ifinitialise aval. A name that is decided once and never reassigned is the strongest guarantee available at this level, and it costs nothing to get.
- Use
iffor two outcomes on a boolean condition andwhenfor three or more, or whenever there is a single subject to switch on. The reader should be able to tell which kind of decision it is from the first word.
- Put a
throwor areturnin the branch that has no answer, instead of a sentinel.Nothingkeeps the result type as narrow as the real answer, and the failure names itself.
- Bind the subject before testing it, so the condition and the value read the same expression once. This matters most with sequences, iterators and anything whose evaluation has a cost or a side effect.
- Decide the type of the result on purpose. If the two branches cannot share a useful type, that is a sign they answer different questions and belong in separate expressions.
- Keep each branch to a single expression or a short block whose last line is obviously the value. When a branch grows past a few lines, give it a name and call it.
- Answer any given business question in exactly one place. When a label and a number both come from the same rule, derive the number from the label rather than testing the raw input twice.
Practice Exercises
- Fix the named flaw in the costing sheet. Keep
bandForas the only place the size question is answered, changediscountForto take the band string rather than the weight, and print the six vats again. Add a closing line that reports how many rows are labelledBULKand how many received the bulk discount, and make sure the two numbers are equal.
- Rewrite
mordantPerKgas awhenoverenum class Fibre { WOOL, SILK, FLAX }with noelse, keep the originalifchain alongside it, then loop over the three fibres printing both answers on one line each and finish with a line saying how many of the three pairs agreed.
- Demonstrate the last-expression rule. Write a function whose
ifhas two braced branches, each declaring a local value and then ending in an arithmetic expression; call it with one input per branch and print both results. Then add a second version in which the arithmetic line comes before the declaration and explain in a comment why it will not compile.
- Add a small-batch surcharge as a fifth
if, charging 150 pence when a vat holds under two kilograms. Print it as a new column, add its own total to the totals row, and finish with a line stating whether mordant plus dye plus surcharge minus discount equals the net total.