A NullPointerException occurs when code dereferences a null reference where an object is required. Kotlin makes this failure less common by tracking nullability in its type system: ordinary types are non-nullable, while a question mark marks a nullable type. Operations that could dereference a nullable value generally fail at compile time instead of reaching production. section 1.4.3 section 7.13
A nullable reference is rejected before execution
fun main() { var s: String? = null // nullable var s2: String = "" // non-nullable println(s.length) // does not compile println(s2.length) // valid } The declaration of s permits null, so direct property access is unsafe. The declaration of s2 promises a non-null String, allowing length to be accessed normally. Kotlin therefore moves this error from runtime into compilation. section 1.4.3
When a value is nullable, Kotlin provides several explicit ways to decide what should happen:
- Use the safe-call operator ?. to access a property or call a method only when the receiver is non-null. section 7.13
- Use the Elvis operator ?: to supply a default, return early, or throw when an expression is null. section 7.13
- Use let with a safe call to operate inside a lambda where the value is treated as non-null. section 7.13
- Use !! only when the non-null promise is justified; breaking that promise produces an exception. section 7.13
The protection is especially useful in JVM applications that interoperate with Java. Kotlin can make existing services more compact, reliable, and maintainable, while its null-aware type system prevents many Java-style null dereferences during compilation. Android development likewise benefits from fewer NullPointerException crashes; Google reported a 30% reduction in Google Home crashes after switching new features to Kotlin. section 1.3.1 section 1.3.2
fun main() {
var s: String? = null #1
var s2: String = "" #2
println(s.length) #3
println(s2.length) #4
}
Compare a nullable String with a non-nullable String and see which property access Kotlin permits. section 1.4.3

