The Analogy: The Coloured Docket at the Bonded Warehouse
A bonded warehouse takes in crates that arrive stencilled with nothing but the word GOODS. That is all the shipping paperwork guarantees, and the warehouse is legally forbidden from assuming any more: a crate stencilled GOODS might hold glassware, might hold tinned fruit, might hold a single machine part packed in straw. Every crate on the floor is, as far as the register is concerned, exactly the same kind of thing. Handling one requires the same caution as handling any other, which means the forklift driver may not stack it, the packer may not open it, and nobody may write a weight against it.
At the gate there is an inspection bench. The inspector prises the lid, looks inside, identifies the contents, and staples a coloured docket to the side of the crate: blue for glassware, green for tinned goods, orange for machine parts. From the moment that docket is stapled on, everybody downstream is entitled to treat the crate as what the docket says without prising the lid again. The forklift driver reads blue and knows not to stack it. The packer reads green and knows a weight is written on the underside. One inspection at the gate buys certainty for the whole journey through the shed, and the docket is trusted precisely because the inspection genuinely happened.
That single-inspection-then-trust arrangement is what Kotlin calls a smart cast. You write one check -- if (crate is Glassware) -- and inside the region where that check is known to hold, the compiler lets you use the crate as glassware with no further ceremony: no second test, no cast operator, no cast exception waiting to happen. The check and the trust are the same act. This is different from prising the lid, throwing the contents on the bench and declaring them glassware by fiat, which is what an unchecked cast does, and which the warehouse would call fraud.
The warehouse has one rule that looks fussy and is not. A docket may only be trusted on a crate that cannot be repacked between the gate and the loading bay. If a crate sits on a repacking line, or if its contents are fetched fresh from a supplier each time somebody looks, the docket is worthless -- it records what was inside at the moment of inspection, and something else may be inside now. The failure this prevents is nasty because it is invisible: the docket is still blue, still stapled on, still perfectly legible, and the crate now holds tinned fruit. Kotlin refuses the smart cast in exactly these cases. A var that a lambda might reassign, a property another thread might overwrite, an open val whose getter a subclass might replace, a val with a custom getter that recomputes on every read: for all of these the compiler says no, because the check and the use are separated by a window in which the answer can change.
Syntax or Core Structure
Three operators do the work: is asks a question, as asserts an answer, and as? asks the question and hands back null instead of throwing when the answer is no.
fun main() {
val crate: Any = "glassware x12"
println("Declared as Any: " + (crate is String))
if (crate is String) {
// smart cast: crate is a String for the rest of this block
println("Length: ${crate.length}")
println("Upper: ${crate.uppercase()}")
}
val asString: String? = crate as? String
val asInt: Int? = crate as? Int
println("as? String succeeded: ${asString != null}")
println("as? Int succeeded: ${asInt != null}")
}
Output:
Declared as Any: true
Length: 13
Upper: GLASSWARE X12
as? String succeeded: true
as? Int succeeded: false
Count the string if you like: nine letters, one space, three characters of x12, which is 13. The line that matters is the one inside the if. Nothing in it repeats the type test and nothing in it casts, yet crate.length compiles even though crate was declared Any -- and Any has no length. The is check on the line above is what made length reachable, and only within that block. Move the println one line below the closing brace and it stops compiling.
Technical Depth: What the Compiler Knows, and For How Long
The built-in types and what they become
Kotlin has no separate primitive and wrapper vocabulary. There is one Int, and whether it lands as a JVM int or a java.lang.Integer depends on whether it is nullable, boxed into a generic container, or used as a receiver for a nullable-typed call.
| Kotlin type | Range or shape | JVM form when non-null |
|---|---|---|
| Byte | 8-bit signed, -128 to 127 | byte |
| Short | 16-bit signed, -32768 to 32767 | short |
| Int | 32-bit signed | int |
| Long | 64-bit signed | long |
| Float | 32-bit IEEE 754 | float |
| Double | 64-bit IEEE 754 | double |
| Char | one 16-bit UTF-16 code unit | char |
| Boolean | true or false | boolean |
| String | immutable sequence of Char | java.lang.String |
Two of these rows regularly surprise people. Char is a single UTF-16 code unit, not a Unicode character, so an emoji is two Char values and length on a string containing one reports 2. And there is no implicit widening anywhere in the table: an Int does not become a Long because the context wants one, which is why toLong() exists and why you will type it more often than you expect.
When a smart cast is allowed
The rule is not about the type being checked; it is about whether the value can change between the check and the use.
| What is being checked | Is a smart cast allowed |
|---|---|
| A local val | yes, nothing can reassign it |
| A local var not captured by a lambda that writes to it | yes |
| A local var captured and written by a lambda | no, the write may happen between check and use |
| A val property in the same module with the default getter | yes |
| An open val property | no, a subclass may override the getter |
| A var property of a class | no, another method or thread may reassign it |
| A val with a custom getter | no, each read may compute a different value |
| A val delegated by lazy or observable | no, the value comes from the delegate |
The workaround for every "no" row is the same and it is not a hack: copy the value into a local val first, then check that. The copy is the moment of inspection, and the local val is a crate that cannot be repacked.
class Gate(val fixed: Any, var movable: Any)
fun describeLocal(value: Any): String {
if (value is String) return "String of length ${value.length}"
if (value is Int) return "Int with square ${value * value}"
if (value is List<*>) return "List of size ${value.size}"
return "unknown: ${value::class.simpleName}"
}
fun main() {
val gate = Gate("bolted", 7)
if (gate.fixed is String) {
// val property, default getter, same module: the smart cast applies
println("fixed length: ${gate.fixed.length}")
}
// movable is a var property, so an is-check cannot narrow it in place.
val snapshot = gate.movable
if (snapshot is Int) {
println("movable doubled: ${snapshot * 2}")
}
println(describeLocal("crate"))
println(describeLocal(12))
println(describeLocal(listOf(1, 2, 3)))
println(describeLocal(3.5))
}
Output:
fixed length: 6
movable doubled: 14
String of length 5
Int with square 144
List of size 3
unknown: Double
The four describeLocal calls show the shape you will write most: a run of is checks with an early return from each. Because each return leaves the function, the compiler knows that any line after a failed check is a line where that type was ruled out, so the checks narrow progressively without nesting. The last line reaches value::class.simpleName, which is available on any value without the reflection library, and reports Double -- the one arrival with no branch of its own.
Any at the top, Nothing at the bottom
Kotlin's type hierarchy has a ceiling and a floor. Any is the supertype of every non-null type, so a parameter typed Any accepts anything except null; Any? accepts that too. Nothing is the subtype of every type and has no values at all, which means an expression of type Nothing cannot return normally. That sounds like a curiosity and is in fact the mechanism that makes throw usable as an expression.
fun fail(reason: String): Nothing = throw IllegalStateException(reason)
fun weight(label: String): Int = when (label) {
"light" -> 10
"medium" -> 50
"heavy" -> 200
else -> fail("no such band: $label")
}
fun main() {
println("light = ${weight("light")}")
println("heavy = ${weight("heavy")}")
val outcome = try {
weight("enormous")
"reached"
} catch (e: IllegalStateException) {
"caught: ${e.message}"
}
println(outcome)
val anything: Any = 42
val nullableAnything: Any? = null
println("Any holds Int: ${anything is Int}")
println("Any? holds null: ${nullableAnything == null}")
}
Output:
light = 10
heavy = 200
caught: no such band: enormous
Any holds Int: true
Any? holds null: true
Look at what Nothing bought. weight is declared to return Int, and its when must therefore produce an Int in every arm -- including the else. fail returns Nothing, and because Nothing is a subtype of Int as it is of everything else, that arm type-checks. No return statement, no unreachable dummy value, no else -> 0 quietly poisoning the totals downstream. The try block underneath then proves the arm really does throw: the string "reached" never becomes the value of the expression, and outcome holds the message instead.
Real World Example: The Gate Inspector's Classification Report
The bonded warehouse gets one delivery a day, and what arrives is genuinely heterogeneous: descriptions, counts, weights, boolean flags from the scanner, gaps where a field was never filled in, and occasionally something nobody recognises. The inspector's job is to staple a docket to each and produce a tally at the end of the shift.
fun classify(item: Any?): String = when (item) {
null -> "MISSING"
is String -> if (item.isBlank()) "BLANK" else "TEXT"
is Int -> if (item < 0) "NEGATIVE" else "COUNT"
is Double -> "WEIGHT"
is Boolean -> if (item) "FLAGGED" else "CLEAR"
is List<*> -> "BUNDLE"
else -> "UNKNOWN"
}
fun main() {
val arrivals: List<Any?> =
listOf("glassware", 12, 3.5, true, null, "", -4, listOf("a", "b"), 'X')
val counts = mutableMapOf<String, Int>()
for (index in arrivals.indices) {
val kind = classify(arrivals[index])
counts[kind] = (counts[kind] ?: 0) + 1
println("slot $index -> $kind")
}
println("--")
for (kind in counts.keys.sorted()) {
println("$kind = ${counts.getValue(kind)}")
}
var total = 0
for (n in counts.values) {
total += n
}
println("classified $total of ${arrivals.size}")
var numericSum = 0.0
for (item in arrivals) {
val asInt = item as? Int
val asDouble = item as? Double
if (asInt != null) numericSum += asInt.toDouble()
if (asDouble != null) numericSum += asDouble
}
println("numeric sum = $numericSum")
}
Output:
slot 0 -> TEXT
slot 1 -> COUNT
slot 2 -> WEIGHT
slot 3 -> FLAGGED
slot 4 -> MISSING
slot 5 -> BLANK
slot 6 -> NEGATIVE
slot 7 -> BUNDLE
slot 8 -> UNKNOWN
--
BLANK = 1
BUNDLE = 1
COUNT = 1
FLAGGED = 1
MISSING = 1
NEGATIVE = 1
TEXT = 1
UNKNOWN = 1
WEIGHT = 1
classified 9 of 9
numeric sum = 11.5
Nine arrivals produce nine dockets and nine distinct kinds, which is why every tally line reads 1 and why the two figures on the classified line agree: the tally counts dockets, arrivals.size counts crates, and if a branch of classify ever failed to fire those numbers would part company. The numeric sum is the arithmetic worth tracing by hand: slot 1 contributes 12, slot 2 contributes 3.5, slot 6 contributes -4, and 12 plus 3.5 minus 4 is 11.5. Nothing else in the list is an Int or a Double; true is not 1 and 'X' is not 88, because as? performs no conversion at all.
The when is doing three separate jobs and it is worth separating them in your head. The null arm is a value test. The is arms are type tests, and each one smart-casts item for the arm's own expression, which is how item.isBlank(), item < 0 and if (item) all compile against a parameter declared Any?. And the nested if inside three of those arms is an ordinary expression producing the arm's value. Because classify has an expression body with a declared String return type, every arm is checked against String and the else is mandatory.
The two type tests worth noticing are the ones that are weaker than they look. is List<*> checks that the value is a list and says nothing about what is in it, because the element type was erased at compile time; the star is Kotlin making that honest rather than letting you write is List<String> and believe it. And is Double will not match an Int, nor is Int a Long, because Kotlin performs no implicit numeric widening -- a fact this program depends on twice, since 12 must land in COUNT and not WEIGHT.
The limits start with scope. This classifies one delivery held entirely in memory, prints as it goes, and would need restructuring the moment the report had to be produced without a console. The design flaw, though, is in numericSum, and it is not a rough edge: the loop adds a count of items, a weight in kilograms, and a negative sentinel into a single Double as if they were commensurable quantities. Twelve crates plus three and a half kilos is not a number that means anything, and the -4 that the classifier itself flagged as NEGATIVE -- a value it has already decided is suspect -- is folded straight into the total instead of being excluded. The reason it survives review is that the code looks careful: it uses as? rather than as, it null-checks both results, and it never throws. Type safety is not unit safety, and as? will not save you from adding apples to kilograms. The honest version keeps two accumulators, or better, refuses to sum at all until the domain types are distinct enough that the compiler can object.
Common Mistakes
- Casting with
aswhen you have already tested withis. Inside a block guarded byif (x is String), writing(x as String).lengthis redundant and the compiler warns about it. The smart cast already happened; the cast operator only adds noise and a second place for the type to be wrong.
- Expecting a smart cast on a
varproperty.if (config.mode is String) config.mode.lengthwill not compile whenmodeis avar. The compiler is not being pedantic: between the two reads another method could reassign it. Snapshot it into a localvaland check that.
- Believing
is List<String>checks the elements. Generic type arguments are erased, so onlyis List<*>is permitted, and it tells you the value is a list and nothing more. Verifying element types requires actually looking at the elements.
- Using
ason data you did not produce. A failedasthrowsClassCastExceptionat that line. For anything crossing a boundary -- parsed JSON, a map lookup, a value from Java --as?and a null check turn a crash into a branch.
- Assuming numeric types widen implicitly.
val n: Long = 42compiles because42is a literal the compiler can type asLong, butval m: Int = 1; val k: Long = mdoes not. There is no implicitInttoLongconversion anywhere in Kotlin; you writem.toLong().
- Treating
Charas a small integer.'X'is not88, andis Intwill not match it. Converting needs'X'.code, and going the other way needs88.toChar().
- Reading
lengthas a count of characters.String.lengthcounts UTF-16 code units. Any character outside the Basic Multilingual Plane occupies two of them, so a string holding one such character reports a length of 2. UsecodePointCountwhen you mean characters.
- Comparing a
Doubleto a literal with==.0.1 + 0.2 == 0.3is false in IEEE 754 and Kotlin will not pretend otherwise. Compare against a tolerance, or hold money and other exact quantities inInt,LongorBigDecimal.
- Adding a nullable type to a hot loop without thinking.
Intis a JVMintand allocates nothing.Int?is ajava.lang.Integerand allocates per boxed value outside the small cached range. One question mark on an accumulator in an inner loop is a measurable regression.
Best Practices
- Prefer
as?plus a null check toaseverywhere data crosses a boundary. The nullable result forces you to write the failure path, which is the path that actually happens in production.
- Snapshot into a local
valbefore checking a property's type. One extra line converts a refused smart cast into an allowed one and documents that you are reasoning about a single observed value.
- Let a
whenwithisarms replace a chain of casts. One subject, one expression, exhaustiveness checked, and each arm smart-casts for free.
- Return
Nothingfrom your failure helpers. A function declared: Nothingcan be used as theelsearm of awhenthat must produce a value, which removes the temptation to invent a sentinel.
- Write explicit types on numeric properties that cross a wire or a schema. Inference will happily give you
Intwhere the database column isbigint; the mismatch shows up as a silent truncation years later.
- Never widen or narrow numbers implicitly in your own APIs. Take the type you mean, and let callers write
toLong(). The visible conversion is the documentation.
- Use
Any?only at real boundaries, and classify immediately. A value typedAny?that travels three functions deep before anyone tests it has erased every guarantee the rest of the file relies on.
- Keep unit-bearing quantities in distinct types once arithmetic gets involved. A
Weightand aCountthat are bothDoublewill eventually be added together, and no type checker will stop it.
Practice Exercises
- Make the sum honest. Rewrite the numeric loop so counts and weights accumulate separately, negative values are excluded and reported, and the program prints three lines: the count total, the weight total, and how many values were rejected. Verify the weight total is 3.5 and the count total is 12 for the original list.
- Break a smart cast on purpose. Add a
var stage: Anyproperty toGate, writeif (gate.stage is String) println(gate.stage.length), and record the compiler's exact message. Then fix it two ways -- once with a localval, once by making the property aval-- and note which of the two you would use if the value genuinely changes over time.
- Probe erasure. Write a function taking
Anythat reports whether the value is a list of strings, and make it correct forlistOf("a"),listOf(1)andemptyList<Int>(). Explain in a comment whyemptyList<Int>()forces you to pick an answer rather than compute one.
- Measure the question mark. Write two loops summing one million values, one accumulating into
Intand one intoInt?with a null check each iteration, and compare their timings. Report the ratio rather than the absolute numbers, and say which JDK and machine produced it.