Type Checks and Casts
Sometimes a value arrives whose exact type you do not know: a receipt line that might be a drink name or a quantity, stored as Any. Kotlin lets you ask "what are you?" and then, in the same breath, use the value as that type.
The rule
is asks and smart-casts; as insists and may crash; as? shrugs null.
is and !is check a type and give a Boolean. The magic is smart casting: once Kotlin has seen the check succeed, it treats the value as that type automatically.
val item: Any = "latte"
if (item is String) {
println(item.uppercase()) // LATTE — no manual cast needed
}
if (item !is Int) {
println("not a quantity")
}Smart casts work when the compiler can be sure the value did not change between the check and the use, for example a local val.
as is an unsafe cast. It tells the compiler "trust me". If you are wrong, the program throws ClassCastException:
val qty: Any = 3
val name = qty as String // crashes: an Int is not a Stringas? is the safe cast. It gives the value on success and null on failure, so the result type is nullable:
val name: String? = qty as? String // null, no crashA cast never converts a value. It only changes how the compiler views an object that already is that type. val n: Any = 3; n as Long throws, because 3 is an Int. To change a number's type, use toLong().
The shortcut
Pick the tool by asking "What should happen if I am wrong?"
- Branch to other code →
iswith smart cast. - Get
nulland handle it →as?. - Crash, because being wrong is a bug →
as.
Ask the type
if (item is String)— the check succeeds for"latte".
The trap is reaching for as out of habit from other languages. In Kotlin, an is check usually makes the cast unnecessary.
Drills
Answer fast — trust the rule.
val x: Any = "mocha". Inside if (x is String) { … }, what can you call?
val x: Any = 5. What does x as? String produce?
val x: Any = 5. What does x as String do?
val n: Any = 3. How do you get a Long with value 3?
Remember
ischecks a type and smart-casts inside the branch.ascrashes on a wrong guess;as?returns null instead.- Casts change the view, not the value: convert numbers with
to…().
