Kotlin Null Safety
Nullable types
Kotlin separates references that can hold null (String?) from those that cannot (String) at the type-system level. Trying to assign null to a non-null type or dereference a nullable value without checking fails at compile time rather than crashing in production with a NullPointerException:
val requiredName: String = "Ada" // never null
var optionalName: String? = null // explicitly nullable with `?`
// optionalName.length // compile error: must handle null first
Safe calls
The safe-call operator (?.) evaluates the property or method only when the receiver is non-null, returning null otherwise. You can chain safe calls across nested objects and pair them with let to run a block only when a value is present:
val length: Int? = optionalName?.length
// `let` executes only when `optionalName` is non-null
optionalName?.let { value ->
println("Length is ${value.length}")
}
Elvis operator
The Elvis operator (?:) converts a nullable expression into a non-null result by providing a fallback value, or by returning/throwing early on the right-hand side:
val displayName: String = optionalName ?: "anonymous"
fun requireUser(id: String?): String {
// Early return keeps the rest of the function smart-cast to non-null `String`
val cleanId = id?.trim() ?: return "guest"
return "user:$cleanId"
}
Defensive design
Prefer non-null types by default and only use nullable types when the domain genuinely allows missing values. Avoid the non-null assertion operator (!!) in production code—it bypasses compiler safety and reintroduces runtime crashes. When interoperating with Java APIs that lack nullability annotations (platform types), assign values to explicit Kotlin types (String?) at the boundary so nulls cannot leak silently into your core logic.
Practice
Practice eliminating !! and handling absence cleanly:
- Declare a nullable
String?and compute its trimmed length safely using?.and?:. - Write a function that uses
id ?: returnso the remaining lines use smart-cast non-null access. - Explain why platform types from unannotated Java libraries should be wrapped at your Kotlin boundary.