Kotlin·Kotlin from syntax to a coroutine app

Null safety

Use nullable types, safe calls, Elvis and smart casts.

Beginner 13 min read Lesson 2 of 300 Challenge included
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.

Nulls.ktKotlin
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

Provide a default

Easy

Use the Elvis operator to default a nullable name to "friend".

KOTLIN · starter
val name: String? = null
Check 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 in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Functions and lambdas
Lesson 2 of 300 · 0% of course