Skip to content
Tutorials Center
My learning

Topics

Lesson 72 of 134 ยท Idiomatic Kotlin

Smart Casts and Contracts

Learn when Kotlin smart casts work and when they fail, how require, check and isNullOrEmpty help the compiler, and how to write contracts with returns implies and callsInPlace.

After you check a type, Kotlin lets you use the value as that type without a cast: if (x is String) println(x.length). After a null check, a String? becomes a String. This is called a smart cast. It is one of the features that makes Kotlin code short and safe, and one of the most confusing the first time it refuses to work: "Smart cast to 'String' is impossible". The reason is always the same: the compiler can only smart cast a value it can prove has not changed between the check and the use.

This lesson explains that proof, lists exactly when it succeeds or fails, shows the idioms that help the compiler (require, check, isNullOrEmpty), and then goes one level deeper into contracts: a way for a function to tell the compiler what it guarantees. You should know null safety and type checks and casts first.

Smart casts at work

The compiler tracks what it learned from checks and applies it in the code those checks guard. It understands is, !is, == null, != null, &&, ||, early return/throw, and when branches:

Kotlin Where smart casts apply

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 smart cast costs nothing at run time beyond the check you already wrote; for casts of a type the compiler already knows is correct it does not even emit a second cast instruction. Think of it as the compiler remembering a fact.

When smart casts fail: the stability rule

A value is stable if the compiler can be sure that nothing changes it between the check and the use. Stable values are:

  • Local vals, always.
  • Local vars that are not changed between the check and the use, and not captured by a lambda that modifies them.
  • A val property that is private or internal (or in the same module), has no custom getter and is not open.
  • Function parameters (they are always like val).

Unstable values are var properties (another thread or a function call could change them), open properties or properties with custom getters (the next read may differ), and properties declared in a different module (the module can change without recompiling you). Here is the typical failure:

Kotlin A mutable property cannot be smart 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 compiler stops with main.kt:6:17: error: smart cast to 'String' is impossible, because 'nickname' is a mutable property that could be mutated concurrently. Between the check and the use, any other code could have set nickname to null. The fix is to read the property once into a local val, which is stable by definition:

Kotlin Three ways to fix a failed smart cast

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 copy has a second benefit beyond making the compiler happy: it makes your code correct under concurrency. If another thread nulls the property after the check, the local copy is still the value you tested.

Local vars are fine as long as the compiler can see no modification in between. A var captured and changed in a lambda that might run later is not stable, because the lambda could run between your check and your use.

Kotlin Local var: stable until something may change it

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.

Helping the compiler: require, check and friends

The standard library functions require, check, requireNotNull, checkNotNull and error do more than throw. If the call returns, the compiler knows the condition held, so what you tested is smart cast afterwards. They are the idiomatic way to turn a nullable input into a non-null one at the top of a function. The same holds for the null-and-empty helpers.

Kotlin Preconditions that smart cast

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.

isNullOrEmpty() is the clearest everyday example. It is an ordinary function in the standard library, yet after if (list.isNullOrEmpty()) return, list is known to be non-null. The compiler cannot see inside the function to know that. The function states it through a contract.

Contracts: telling the compiler what a function guarantees

A contract is a declaration at the start of a function body that describes how its result relates to its arguments. The compiler trusts it without checking it. Two kinds matter in practice:

  1. returns(value) implies (condition): "if I return normally with this value, the condition is true."
  2. callsInPlace(lambda, kind): "I call this lambda exactly once, at most once, at least once, or unknown, and only before I return."

The contract API is still marked experimental for use in your own code, so you need an opt-in. In source, that is the annotation @OptIn(ExperimentalContracts::class), which works here. Without a contract, a custom check function cannot help the caller:

Kotlin A check function without a contract (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 does not look inside isFilled, so after the call input is still String? and input.length is the error main.kt:6:22: error: only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type 'String?'. A contract fixes it:

Kotlin returns implies: a custom smart-casting check

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.

returns(true) implies (text != null) reads: when isFilled returns true, text was not null. returns() implies (n != null) (no value) means: if the function returns at all (instead of throwing), the condition holds, which is exactly the shape of require and check. You can also say returns(false), returnsNotNull() (the result is non-null whenever an argument is), or implies (x is String).

A contract is a promise you make, not a fact the compiler verifies. If the function body does something different, the compiler still believes the contract and your program fails later, at a different place, with an error that looks impossible. Treat contracts like unsafe code: keep them tiny, and test them.

Here is what a wrong contract does. The body returns true for a null input, and the compiler trusts the contract anyway, so a smart cast crash follows:

Kotlin A lying contract (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 program compiles, and at run time input.length throws java.lang.NullPointerException: Cannot invoke "String.length()" because "input" is null even though input seems to have a non-null type. The compiler cannot catch this. That is why most application code should not define contracts at all, and library authors write them with care.

callsInPlace: lambdas and definite assignment

Another contract kind lets you initialize a val inside a lambda. Normally the compiler must assume a lambda may run any number of times (or never), so it rejects val x: Int assigned inside one. With callsInPlace(block, InvocationKind.EXACTLY_ONCE) it knows the lambda runs exactly once, immediately. This is how the standard run, let, apply and also can initialize variables:

Kotlin Initializing a val inside a lambda

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.

If you remove the contract from runOnce, the compiler reports error: 'val' cannot be reassigned. at the assignment and error: variable 'count' must be initialized. at the use, because it must assume the lambda could run several times or never. That is the whole value of callsInPlace: definite assignment and smart casts of variables changed inside the lambda.

Reading the standard library's contracts

You do not need to write contracts to benefit from them. These standard functions all declare one, and that is why code like the following just works:

  • require(cond) and check(cond): if they return, cond is true (returns() implies cond).
  • requireNotNull(x), checkNotNull(x): the result is non-null, and x is smart cast afterwards.
  • isNullOrEmpty(), isNullOrBlank(), isNotEmpty(): returns(false) implies (this != null) and similar.
  • run, let, apply, also, with, repeat, synchronized, use, measureTime: callsInPlace(..., EXACTLY_ONCE) (or AT_LEAST_ONCE for loops of repeat).
  • error(message) and TODO(): return type Nothing, so code after them is unreachable and the compiler treats branches that end with them as non-returning.
Kotlin Nothing and early exits as smart cast helpers

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.

Notice how each guard line removes one source of null or invalid state and the rest of the function reads as the "happy path" with plain, non-null types. See require, check and assert for the exception types they throw.

Pitfalls and habits

  • Smart cast impossible on a property? Copy it into a local val first; this is also the thread-safe approach.
  • Do not fight the compiler with !!. A message like "smart cast impossible" usually tells you that a value can change, which is real information.
  • Platform types (values from Java) have no null checks to learn from; give them a Kotlin type explicitly.
  • is with generics only works for the erased type: x is List<String> fails with cannot check for instance of erased type 'List<String>', use x is List<*>. See Type Erasure and reified.
  • Smart casts after ||: if (x == null || x.isEmpty()) works because the right side only runs when the left is false, but if (x != null || x.isEmpty()) does not compile.
  • Avoid writing contracts in application code. Prefer plain functions that return the narrowed value (fun requireFilled(t: String?): String), which are verified by the compiler.
  • Order of checks matters: put the cheap null check first so the later conditions can rely on it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which value can the compiler always smart cast after a check?

    A local val can never change after initialization, so the compiler knows the checked fact stays true. The other values may change or return different values on each access.
  2. 2. What is the most robust fix for Smart cast to 'String' is impossible on a var property?

    A local copy is stable and also avoids races: you keep working with the value you tested.
  3. 3. What does returns() implies (n != null) promise?

    With no argument, returns() means 'returns normally, without throwing'. This is the shape of require and check.
  4. 4. What happens if a contract states something the function body does not do?

    Contracts are not verified. A wrong contract leads to wrong smart casts and surprising exceptions elsewhere.
  5. 5. Why can run { greeting = "hi" } initialize a val greeting: String?

    The contract tells the compiler that the lambda runs exactly once, in place, so the assignment is definite.

Summary

  • A smart cast lets you use a checked value as the narrower type; it works for is, null checks, &&/||, early exits and when.
  • It only applies to stable values: local vals, unmodified local vars, parameters, and same-module val properties without custom getters.
  • For var properties, copy to a local val or use ?.let.
  • require, check, requireNotNull and isNullOrEmpty use contracts so the compiler learns from them.
  • returns(...) implies (...) and callsInPlace(...) are the two practical contract forms; they need @OptIn(ExperimentalContracts::class).
  • Contracts are unchecked promises: keep them small, rare and tested.

Next: Annotations