Null Safety: Kotlin's Killer Feature

Harry · 14 Sep 2026 · 3 views
Advertisement
Advertisement

Two kinds of types

In Kotlin, a type either can hold null or it cannot, and that difference is enforced by the compiler. A plain String can never be null; a String? (with the question mark) can.

var a: String = "hello"
a = null            // compile error!

var b: String? = "hello"
b = null            // fine

Non-null String versus nullable String? and how each is accessed

Working with nullable values

The compiler forces you to handle the null case before using a nullable value. Three tools do the job:

val len = b?.length            // safe call: null if b is null
val len2 = b?.length ?: 0      // Elvis operator: default when null
b?.let { println(it.length) }  // run a block only if not null
  • ?. is the safe call – it returns null instead of throwing.
  • ?: is the Elvis operator – supply a fallback value.
  • let runs a block only when the value is present.

The not-null assertion (use sparingly)

!! forces a nullable to non-null and throws if it really is null. It is an escape hatch – reaching for it often means the type should not have been nullable:

val forced = b!!.length   // throws NPE if b is null

Why this matters

Because nullability is part of the type, whole classes of runtime crashes become compile errors. You cannot accidentally call a method on something that might be null – the compiler stops you until you have handled it.

Key points

  • Type can never be null; Type? can – the compiler enforces the difference.
  • Use ?. for safe calls and ?: to supply defaults.
  • let runs code only when a value is present.
  • Avoid !! – needing it usually signals a design that should be non-null.
Share this post:

Comments (0)

Please login or register to comment.