Tsallaka zuwa abun ciki
Justice Tech School

Type Checks and Smart Casts

is tests a type, and after the test Kotlin smart casts the value automatically. as casts explicitly and as? returns null on failure.

Example
fun describe(x: Any) = when (x) { is Int -> "int ${x + 1}"; is String -> "text ${x.length}"; else -> "other" }
println(describe(5))
println(describe("hey"))
val n = "7" as? Int
println(n)

Exercise

Test a type.

if (x  String)

Quiz Test

What does as? return on failure?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.