← Back to Kotlin Course | Chapter 2: Variables & Types | Lesson 7 of 7

Type Checking and Casting

Type checking and casting let your code ask 'what kind of thing is this?' and then safely treat it as that specific kind.

Checking Types with is

The is operator checks whether a value is an instance of a given type at runtime, returning true or false, similar to instanceof in Java.

Example: Checking Types with is

markup
fun describe(value: Any) {
    if (value is String) {
        println("It is a String of length ${value.length}")
    } else {
        println("Not a String")
    }
}

fun main() {
    describe("Kotlin")
    describe(42)
}

Smart Casts

Once an is check confirms a value's type, Kotlin automatically treats it as that type for the rest of that scope -- no manual cast is needed, which is called a smart cast.

Example: Smart Casts

markup
fun printLength(value: Any) {
    if (value is String) {
        // value is smart-cast to String here
        println("Length: ${value.length}")
    }
}

fun main() {
    printLength("Hello")
}

Unsafe Cast with as

The as operator forcibly casts a value to a given type, throwing a ClassCastException at runtime if the value is not actually compatible with that type.

Note: Only use as when you are certain of the type; otherwise prefer as?.

Example: Unsafe Cast with as

markup
fun main() {
    val value: Any = "Kotlin"
    val text = value as String
    println("Cast succeeded: $text")
}

Safe Cast with as?

The as? operator attempts the same cast but returns null instead of throwing when it fails, which is much safer when the type is uncertain.

Example: Safe Cast with as?

markup
fun main() {
    val value: Any = 42
    val text = value as? String
    println("Safe cast result: $text")
}
Common Mistakes
  1. Using the unsafe cast as on a value that might not actually be that type, causing a ClassCastException at runtime.
  2. Not using smart casting after an is check, and casting manually anyway, producing more verbose code than necessary.
  3. Forgetting that as? returns null instead of throwing, and not handling that null result.
Chapter Summary
  • is checks whether a value is a certain type at runtime, returning a Boolean.
  • Kotlin's smart casts automatically treat a value as the checked type inside an if (x is Type) block, without a manual cast.
  • as performs an unsafe cast that throws ClassCastException if the value is not actually that type.
  • as? performs a safe cast that returns null instead of throwing when the cast is not possible.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.