Skip to content

Null safety and smart casts

Null Safety and Smart Casts Deep Dive

Overview

Null safety is one of Kotlin's biggest value propositions. It moves many null-related problems from runtime into the type system.


Core Concepts

Kotlin distinguishes:

  • String โ†’ non-nullable
  • String? โ†’ nullable

Main tools:

  • safe call ?.
  • Elvis ?:
  • not-null assertion !!
  • smart casts after checks

Internal Implementation

Kotlin null safety is mostly compiler enforced. The type system tracks nullable vs non-nullable references and emits checks where needed.

Platform types from Java weaken these guarantees because nullability may be unknown at compile time.


JVM / Compiler Behavior

The compiler often inserts runtime null-checks for parameters and assumptions, especially around Java interop and non-null contracts.

Smart casts rely on flow analysis. They work only when the compiler can prove the reference is stable.


Code Examples

val name: String? = input()
val length = name?.length ?: 0
if (value is String) {
    println(value.length) // smart cast
}

Common Interview Questions

  • Q: Why can null still happen in Kotlin? A: Connect Kotlin features to outcomes: safer APIs through nullability, clearer state modeling, and awareness of generated bytecode and allocation cost.
  • Q: What is a platform type? A: Tie Kotlin language features to production outcomes: safety, readability, testability, and runtime or allocation tradeoffs when relevant.
  • Q: When do smart casts fail? A: Tie Kotlin language features to production outcomes: safety, readability, testability, and runtime or allocation tradeoffs when relevant.
  • Q: Why is !! dangerous? A: Tie Kotlin language features to production outcomes: safety, readability, testability, and runtime or allocation tradeoffs when relevant.

Production Considerations

  • avoid !! unless failure is intentional
  • make nullability explicit in public APIs
  • be careful at Java boundaries
  • prefer safe transformations to assertions

Performance Insights

Null safety is primarily a correctness feature. Runtime cost is usually minor compared with the stability benefit.


Senior-Level Insights

Good candidates explain that Kotlin reduces null problems significantly, but cannot eliminate them when unsafe assertions, Java interop, reflection, or poor API design are involved.