Smart Casts Workbook
Practice problems for Kotlin Smart Casts. Each takes a minute or two. Write your own answer first, then click Show answer — nothing here is a trick question, just direct practice of the syntax from the lesson.
the basic cast
1. Check, then use
Given x: Any, print its length when it’s a String — without writing a cast.
Show answer Hide answer
if (x is String) {
println(x.length) // x is smart-cast to String here
} 2. Negate and return early
Given x: Any, return early when it is not a String; afterward, use it as a String.
Show answer Hide answer
if (x !is String) return
println(x.length) // x is String from here on 3. Null check narrows
Given name: String?, print its length only when it isn’t null — no safe call, no !!.
Show answer Hide answer
if (name != null) {
println(name.length) // name is smart-cast to String
} in when and conditions
4. Smart cast inside when
Given x: Any, return x + 1 if it’s an Int, else 0. Use the smart cast.
Show answer Hide answer
when (x) {
is Int -> x + 1
else -> 0
} 5. Combined condition
Given x: Any, return true only when x is a non-empty String.
Show answer Hide answer
x is String && x.isNotEmpty()After the is check on the left, x is smart-cast for the right-hand side.
6. Elvis with an early exit
Given value: Any, bind a String named s or return early if value isn’t one. Use a safe cast.
Show answer Hide answer
val s = value as? String ?: return
println(s.uppercase()) the edges
7. Why won’t this smart-cast?
This fails to compile: a nullable var property name accessed as name.length after a null check. Why, and how do you fix it?
Show answer Hide answer
A var property could change between the check and the use, so the compiler won’t smart-cast it. Copy it into a local val first:
val n = name
if (n != null) println(n.length) 8. After a throw
Given config: Config?, throw IllegalStateException when it’s null; afterward use it as non-null.
Show answer Hide answer
if (config == null) throw IllegalStateException("missing config")
config.load() // config is non-null here 9. When smart casts can’t help
You only have a val x: Any, and you’re certain it’s a String, but there’s no check in the code path. Write the explicit cast to call .length.
Show answer Hide answer
(x as String).lengthA plain as throws if you’re wrong; prefer a checked is or a safe as? when you aren’t certain.
10. Combine type and null
Given x: Any?, return its length when it is a non-null String, else -1.
Show answer Hide answer
if (x is String) x.length else -1A smart cast to String also rules out null, since String is non-nullable.
Back to the lesson, Kotlin Smart Casts, or on to the next one: null safety.
Comments