Member-only story
Kotlin / Contracts
How to Make the Compiler Smarter
Add effects to your functions with Kotlin Contracts

Introduction
The Kotlin compiler is smart. By performing static analysis on your code, the compiler identifies mistakes in your code as you type it.
One of the most notable features of the Kotlin compiler is smart casting. The compiler has the ability to perform a cast based on the type checks done by the developer.
The compiler tracks the is
-checks, null-checks, and explicit casts for immutable values. Using the acquired information, the compiler casts variables when needed.
However, the smart cast mechanism is limited. The compiler does not cast variables when the variable can change between the check and the usage.
Moreover, the compiler tracks the type checks only in the same block or in the same condition in which the check was performed.
The compiler is not THAT smart…
In your codebase, you have a better understanding of what can happen and what cannot.
Wouldn’t it be nice if you could somehow transfer this knowledge to the compiler?
Kotlin Contracts

With Kotlin Contracts, you can “sign an agreement” between you and the compiler — if something goes wrong, the compiler will “sue” you (by crashing the application).
However, Contracts are deterministic and describe the natural effect of your code, hence it is highly…