CodeToLive

Kotlin Null Safety

Understand Kotlin's null safety features to eliminate NullPointerExceptions.

Nullable Types

// Regular (non-null) type
var name: String = "Kotlin"
name = null  // Compilation error

// Nullable type
var nullableName: String? = "Kotlin"
nullableName = null  // Valid

Safe Calls (?.)

val length = nullableName?.length  // Returns null if nullableName is null

// Chain safe calls
val streetLength = user?.address?.street?.length

Elvis Operator (?:)

// Provide default value if null
val nameLength = nullableName?.length ?: 0

// Throw exception if null
val nonNullName = nullableName ?: throw IllegalArgumentException("Name required")

Non-null Assertion (!!)

// Force non-null (throws NPE if null)
val forcedLength = nullableName!!.length

Safe Casts (as?)

val obj: Any = "Hello"
val str: String? = obj as? String  // Safe cast returns null if fails
val num: Int? = obj as? Int       // Returns null

Let Function

nullableName?.let { name ->
    // Executes only if nullableName is not null
    println(name.length)
}

Platform Types

// Java interop - annotate with @Nullable/@NotNull
// Java:
// @Nullable String getName() { ... }

// Kotlin:
val name = javaObj.getName()  // Inferred as String?
name?.length
← Back to Tutorials