Careeroza
Nullable Types
The Billion-Dollar Mistake
In Java any object reference can be null. Calling a method on it crashes the app with a NullPointerException (NPE) — for years the most common Android crash. Kotlin fixes this in the type system:
String— can never holdnull.String?— a nullable type: can hold a string ornull.
var name: String = "Asha"
name = null // ERROR: Null can not be a value of a non-null type String
var nickname: String? = "Ash"
nickname = null // OK
println(nickname.length) // ERROR: Only safe (?.) or non-null asserted (!!.) calls are allowedChecking for null
Example
After an if (x != null) check, Kotlin smart casts the variable to the non-null type inside the block.
fun main() {
val middleName: String? = null
val city: String? = "Hyderabad"
if (middleName != null) {
println("Middle name length: ${middleName.length}")
} else {
println("No middle name")
}
if (city != null) {
println("City has ${city.length} letters") // smart cast to String
}
}Output
No middle name City has 9 letters
Java vs Kotlin
| Java | Kotlin | |
|---|---|---|
| Can a normal reference be null? | yes, always | no |
| How to allow null | nothing to do | add ? to the type |
| When is the NPE found? | at run time (crash) | at compile time (error in the IDE) |
| Null checks | if (x != null) everywhere | ?., ?:, let |