Kotlin Tutorial · Kotlin Basics · Lesson 10 of 31
Kotlin Null Safety
Nullable types, safe calls, the Elvis operator, smart casts and why Kotlin code rarely throws NullPointerException.
Nullable types
A normal type can't hold null: val name: String = null doesn't compile. Add ? to allow it:
String?. The compiler then makes you handle the null case before you use the value.
fun main() {
var nickname: String? = null
println(nickname?.length) // safe call: null
nickname = "Ana"
if (nickname != null) {
println(nickname.length) // smart cast: nickname is String here
}
}
Output
null 3
Run this on your computer — see “Get Started” for setup.
Operators for nulls
?.safe call: calls only if the value isn't null, otherwise the result isnull.?:Elvis operator: a fallback when the left side is null (it can alsoreturnorthrow).!!asserts non-null and throws if it is null; avoid it.?.let { }runs a block only for non-null values.
data class User(val name: String, val email: String?)
fun domainOf(user: User): String {
val email = user.email ?: return "no email"
return email.substringAfter("@")
}
fun main() {
val users = listOf(User("Ana", "[email protected]"), User("Ben", null))
for (u in users) {
println("${u.name}: ${u.email?.uppercase() ?: "(none)"}")
u.email?.let { println(" send welcome mail to $it") }
println(" domain: ${domainOf(u)}")
}
println("42".toIntOrNull() ?: 0)
println("x".toIntOrNull() ?: 0)
}
Output
Ana: [email protected] send welcome mail to [email protected] domain: example.com Ben: (none) domain: no email 42 0
Run this on your computer — see “Get Started” for setup.
Test yourself
What does a ?: b evaluate to when a is null?
nullba NullPointerExceptionfalse
Show answer
Answer: b