Nullable Types in Kotlin
From the Kotlin cheat sheet · Null Safety · verified Jul 2026
Nullable Types
Working with nullable types safely
kotlin
// Nullable types
var nullable: String? = "Hello"
nullable = null // OK
var nonNull: String = "Hello"
// nonNull = null // Error: Null cannot be assigned
// Safe call operator
val length = nullable?.length // Returns null if nullable is null
// Elvis operator
val lengthOrZero = nullable?.length ?: 0
val message = nullable ?: "Default message"
// Not-null assertion (use sparingly!)
val forceLength = nullable!!.length // Throws NPE if null
// Safe casts
val any: Any = "String"
val str: String? = any as? String // Safe cast
val num: Int? = any as? Int // Returns null💡 ? makes a type nullable, safe call ?. prevents NPE
⚡ Elvis operator ?: provides default for null values
📌 Avoid !! (not-null assertion) - it defeats null safety
🟢 Smart casts eliminate need for explicit casting after null check