Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 134 ยท Control Flow

Type Checks and Casts

Learn Kotlin type checks and casts - is and !is, smart casts, as and as?, ClassCastException, Any, generic erasure and star projections, with runnable examples and real error messages.

Sometimes a value arrives with a general type, and you need to find out what it really is. A list of mixed items is declared List<Any>. A function receives a Shape and must treat circles and rectangles differently. A parser returns Any? and you want to know whether it found a number or a word. Kotlin gives you two things for this: type checks with is, and casts with as and as?. Better still, after a successful check the compiler automatically treats the value as the more specific type, a feature called smart casting.

This lesson shows how all of it works, why a cast can fail at run time, how generics limit what you can check, and when to avoid casting altogether by choosing a better design.

Any: the root of the type hierarchy

Every non-null Kotlin type is a subtype of Any. A variable of type Any can hold a string, a number, a list, or an object of your own class. Any? additionally allows null. (The relationship between Any, Unit and Nothing has its own lesson: Any, Unit and Nothing.)

The catch is that, through an Any variable, you can only use what every object has: toString(), equals() and hashCode(). To use anything more specific you must find out the actual type.

Kotlin What can you do with an Any?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

thing::class.simpleName asks the object for its class at run time (this uses a small part of reflection that is always available; the full reflection API is covered in Reflection Overview). The list prints String, Int, Double, Boolean, Char and ArrayList: the runtime class, not the declared type Any.

is and !is

The is operator checks the runtime type and returns a Boolean. !is is the negation.

Kotlin Checking types with is

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Look closely at what happens inside the if branches. In value.length we call a String member on a variable declared as Any. That is legal because the compiler has smart cast value to String in that branch. You did not write a cast, and you did not create a new variable.

How smart casts work

A smart cast is the compiler remembering what a check proved. It works in more places than beginners expect:

  • after if (x is T), inside the branch;
  • on the right of && (x is String && x.length > 3) and on the right of || for a negative check (x !is String || x.isEmpty());
  • after an early exit, such as if (x !is T) return, for the rest of the function;
  • in every branch of a when with is conditions;
  • in loops and conditions like while (x is T).
Kotlin Smart casts in &&, early exits and when

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The when form is the most common way to branch on type. It is covered in detail in when Expressions, and when the types form a closed set it becomes the engine of sealed classes, where the compiler checks that you handled every case.

When a smart cast is refused

Smart casts need the compiler to be sure the value cannot change between the check and the use. They work on local vals, on local vars that are not modified in between (and not captured in a lambda that modifies them), and on val properties of the same module that have no custom getter. They do not work on var properties or on properties declared in another module. This is the same rule as for null checks in Null Safety. When a smart cast is refused, copy the value into a local val:

Kotlin Smart cast on a mutable property (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler reports smart cast to 'String' is impossible, because 'content' is a mutable property that could be mutated concurrently. The fix:

Kotlin The fix: a local snapshot

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Casts: as

Sometimes you know more than the compiler. The unsafe cast x as T converts x to T, and throws ClassCastException if it is not one.

Kotlin A failing cast (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is before the cast, then the run stops with java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer, followed by the module details Java appends. A ClassCastException is the type-system version of a NullPointerException: you asserted something and were wrong.

If the value is null and the target type is non-null, as throws too, with a different exception (NullPointerException, with a message that null cannot be cast to non-null type). Cast to a nullable type, x as String?, if null is acceptable.

Safe casts: as?

as? returns the converted value, or null when the cast is impossible. It never throws. Combined with ?: or ?. it replaces most explicit type checks:

Kotlin as? with Elvis and safe calls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

A good rule: use as? when failure is a normal, expected case, and use as only when failure would mean a bug in your program. For a bug you often want a better error than ClassCastException anyway: checkNotNull, require and error() let you write your own message (see require, check and assert).

Incompatible checks are compile errors

When the compiler can see that a check can never succeed, it refuses it. This catches typos and logic errors:

Kotlin An impossible is check (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler reports main.kt:3:9: error: check for instance is always 'false'. It is an error, not just a warning. If the declared type were Any, the check would be legal, since an Any can hold an Int.

Generics and type erasure

On the JVM, generic type arguments are erased at run time: a List<String> and a List<Int> are both just List. Therefore, you cannot test or cast to a generic type with a specific argument.

Kotlin Checking a generic type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler says main.kt:3:17: error: cannot check for instance of erased type 'List<String>'. What you can check is the generic class with a star projection, List<*>, which means "a list of something". Then check the elements yourself:

Kotlin Star projections and checking elements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

filterIsInstance<String>() keeps only the elements that are strings and returns a List<String>. It works because the type argument is reified in an inline function, which is how Kotlin works around erasure in some cases; see Type Erasure and reified. A cast such as data as List<String> compiles with an unchecked cast warning and does not verify the elements, so a wrong list fails later with a ClassCastException at some unrelated line.

Unit and Nothing in type checks

Two special types have a role here. Unit is the return type of functions that return nothing useful, and its only value is Unit itself. Nothing has no values at all; throw and return have this type, so an expression like x as? String ?: return type-checks. They are explained fully in Any, Unit and Nothing.

Design: avoid casting when you can

Heavy use of is and as is often a sign that the type hierarchy could carry the behavior. Compare:

Kotlin Type checks versus polymorphism

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

areaByChecks must be edited every time a new shape appears, and else hides the forgotten case until run time. The virtual method area() needs no checks at all. Type checks are the right tool when:

  • you receive data of unknown shape from outside (parsed input, Any? from a library, deserialized values);
  • you use a sealed hierarchy and want the compiler to verify that you cover all cases, as in Sealed Classes and Interfaces;
  • you implement equals, where other as? Point ?: return false is the idiomatic first line.

A reliable pattern for equals: if (other !is Point) return false, after which other is smart-cast to Point, so you can compare fields directly. See Equality and Identity.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After if (x is String) { ... }, what can you do with x inside the braces?

    The compiler smart-casts x to String inside the branch, so String members are available directly.
  2. 2. If val v: Any = "text", what does v as? Int evaluate to?

    The safe cast operator as? returns null instead of throwing when the value is not of the target type.
  3. 3. Why is if (data is List<String>) rejected when data is Any?

    At run time all lists are just List. Use List<*> and check the elements, or filterIsInstance.
  4. 4. Which situation makes a smart cast on a property impossible?

    A mutable property might be modified between check and use, so the compiler refuses the smart cast. Copy it into a local val.
  5. 5. When is as (not as?) the better choice?

    Use as? for expected failure and as for 'this must be true or the program is broken'. Even then, a custom error message is often clearer than ClassCastException.

Summary

  • is and !is check the runtime type; after a successful check the compiler smart-casts the variable inside the branch (and after early exits).
  • Smart casts need a stable value: local vals, unmodified local vars, and val properties without custom getters; copy mutable properties into a local val.
  • x as T throws ClassCastException on failure; x as? T returns null, which pairs well with ?: and ?..
  • Generic arguments are erased: check List<*> and filter the elements, for example with filterIsInstance.
  • The compiler rejects is checks that can never succeed.
  • Prefer polymorphism or sealed hierarchies to long chains of casts.

Next: Exceptions