Kotlin's type system is designed to eliminate the danger of null references from code. In Kotlin, a variable cannot hold null unless you explicitly declare it as nullable using the ? suffix. This prevents NullPointerExceptions at compile time.
Kotlin
Beginner
10 min read
Null Safety in Kotlin
Example
fun main() {
// Non-nullable string
var name: String = "Alice"
// name = null // Compile error!
// Nullable string
var nullableName: String? = "Bob"
nullableName = null // OK
// Safe call operator ?.
val length = nullableName?.length // null if nullableName is null
println("Length: $length")
// Elvis operator ?: (provide default)
val displayName = nullableName ?: "Anonymous"
println(displayName)
// Not-null assertion !! (throws exception if null)
val nonNullable = nullableName!! // throws if null — use carefully
// let for null-safe blocks
nullableName?.let { n ->
println("Name is not null: $n")
} ?: println("Name is null")
// Smart cast after null check
if (nullableName != null) {
println(nullableName.length) // auto-cast to String
}
}