Getting Started
Null Safety
Understand Kotlin's null safety system that eliminates NullPointerExceptions at compile time.
Null Safety in Kotlin
In Kotlin, all types are non-null by default. You must explicitly opt in to nullable types with ?.
This eliminates the dreaded NullPointerException — Java's most common runtime error.
Nullable Types
String— cannot be nullString?— can be null
Safe Operators
?.— safe call: only calls if not null?:— Elvis operator: provide a default if null!!— non-null assertion: throws NPE if null (use with care)let— execute block only if not null
Example
kotlin
// Non-nullable (default)
val name: String = "Alice"
// name = null // Compile error!
// Nullable type
var nullableName: String? = null
nullableName = "Bob"
// Safe call operator ?.
println(nullableName?.length) // null if nullableName is null
println(nullableName?.uppercase()?.take(3)) // chaining
// Elvis operator ?:
val length = nullableName?.length ?: 0 // 0 if null
val displayName = nullableName ?: "Anonymous"
// let - execute block only if not null
nullableName?.let { name ->
println("Name is: $name")
println("Upper: ${name.uppercase()}")
}
// !! - non-null assertion (avoid when possible)
val definitelyNotNull: String = nullableName!! // NPE if null
// Smart casts
fun printLength(value: String?) {
if (value != null) {
// Smart cast: value is now String (not String?)
println(value.length)
}
}
// Safe cast
val obj: Any = "Hello"
val str: String? = obj as? String // null if cast fails
val num: Int? = obj as? Int // null (obj is not Int)Try it yourself — KOTLIN