Skip to content
Commitwise
Menu

Smart cast

Kotlin treats a value as a more specific type after you've checked it, without an explicit cast.

Definition

After a check like if (name != null) or if (shape is Circle), Kotlin automatically treats the value as String or Circle inside that block. It only works when the compiler can prove the value can't change between the check and the use, so it works for local vals but not for mutable properties (var) that another thread or a custom getter could change.

In practice

if (user.email != null) sendTo(user.email) fails to compile when email is a var property; user.email?.let { sendTo(it) } works.

Learn it in context

Lessons that use this term.

Related terms

Esc

Type to search the whole site.