Cheat Sheets

Kotlin Null Safety Cheat Sheet: ?, ?:, let, !! and Safe Calls

By ArpaNeuro Team September 18, 2026
Kotlin null safety cheat sheet

Kotlin’s type system distinguishes String from String?. You cannot call methods on a nullable type without ?., a smart cast after a check, or !!. Prefer ?. and ?: fallbacks. !! is a crash on null — use it only when a null would already be a programmer error you want to fail fast.

This Kotlin cheat sheet is written for people searching for a fast, accurate reference: students, junior developers, and teams shipping production software. Pin it, copy the snippets, and come back when syntax slips.

Quick reference

  • Declare: val name: String? = null. Non-null String cannot hold null.
  • Safe call: user?.email?.length chains; any null yields null.
  • Elvis: val x = n ?: 0 if the left is null.
  • let: value?.let { use(it) } runs only when non-null.
  • Smart cast: if (x != null) x.length inside the same thread/module for immutable locals.
  • !!: x!! throws NullPointerException if x is null.
  • lateinit: Non-null var initialized later. ::x.isInitialized to check. Not for primitives.
  • lazy: val x by lazy { compute() } — initialized on first read, thread-safe by default.

Copy-paste examples

Safe user label without !!

Smart casts fail on var that could change. Copy to a local val or use ?..

data class Profile(val name: String?, val city: String?)

fun label(profile: Profile?): String {
    val name = profile?.name?.takeIf { it.isNotBlank() } ?: "Guest"
    val city = profile?.city ?: "Unknown"
    return "$name · $city"
}

fun requireId(id: String?): String =
    requireNotNull(id) { "id missing" }

Common mistakes

  • Sprinkling !! to “make it compile.”
  • Using lateinit for values that can actually be absent — that is a nullable type.
  • Smart-casting a mutable property (var) from another thread or getter.
  • Calling Java APIs and assigning to non-null Kotlin types without a null check.

FAQ

  1. Why did smart cast fail? The compiler cannot prove a var or a custom getter stayed non-null. Use a local val or ?.let.
  1. null vs empty string? Different. null is absence. "" is present but blank. isNullOrBlank() covers both for text fields.
  1. Optionals like Java Optional? Rare in Kotlin. Prefer T?. Optional appears at some Java boundaries.

Related Kotlin cheat sheets

Build with this stack

When a cheat sheet is not enough — you need a production app, a student FYP, or a custom dashboard — ArpaNeuro builds mobile app development and also sells ready-made source code. Request a quote and tell us the stack.

Browse software development services or the source code marketplace if you want a working codebase instead of starting from a blank file.

← All Articles Get a Quote →