Null safety
Use nullable types, safe calls, Elvis and smart casts.
What you will be able to do
- Add ? to allow null.
- Use ?. to call safely.
- Use ?: to provide a default.
- Avoid !! in production code.
In plain English
Kotlin separates nullable and non-null types. A String cannot be null; String? can. Use ?. for safe calls, ?: for defaults and !!. only when you can prove non-null.
fun greet(name: String?): String {
val safe = name?.trim()?.takeIf { it.isNotEmpty() } ?: "friend"
return "Hello, $safe"
}
fun main() {
println(greet(null))
println(greet(" Ada "))
}Your turn
EasyProvide a default
Use the Elvis operator to default a nullable name to "friend".
KOTLIN · starter
val name: String? = nullCheck your understanding before moving on.
Knowledge checkQuestion 1
What does ?. do?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.