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-nullStringcannot hold null. - Safe call:
user?.email?.lengthchains; any null yields null. - Elvis:
val x = n ?: 0if the left is null. - let:
value?.let { use(it) }runs only when non-null. - Smart cast:
if (x != null) x.lengthinside the same thread/module for immutable locals. - !!:
x!!throwsNullPointerExceptionif x is null. - lateinit: Non-null var initialized later.
::x.isInitializedto 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
lateinitfor 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
- Why did smart cast fail? The compiler cannot prove a
varor a custom getter stayed non-null. Use a localvalor?.let.
- null vs empty string? Different.
nullis absence.""is present but blank.isNullOrBlank()covers both for text fields.
- Optionals like Java Optional? Rare in Kotlin. Prefer
T?.Optionalappears 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.