📖 Scenario: Imagine you are building a simple contact list app. Sometimes, a contact might not have a phone number saved. You want to make sure your app does not crash when it tries to use a missing phone number.
🎯 Goal: You will learn how Kotlin's null safety helps prevent errors by forcing you to handle missing (null) values safely.
📋 What You'll Learn
Create a variable that can hold a phone number or no number (null)
Create a variable that cannot hold null
Use safe call operator to access the phone number safely
Use the Elvis operator to provide a default message if the phone number is missing
Print the results to see how Kotlin handles null safety
💡 Why This Matters
🌍 Real World
Apps often deal with missing or optional data like phone numbers or emails. Kotlin's null safety helps avoid crashes by making you handle these cases explicitly.
💼 Career
Understanding null safety is essential for Kotlin developers to write safe, reliable apps and avoid common runtime errors.
Progress0 / 4 steps
1
Create a nullable phone number variable
Create a variable called phoneNumber of type String? and set it to null.
Kotlin
Hint
Use String? to allow the variable to hold null.
2
Create a non-nullable contact name variable
Create a variable called contactName of type String and set it to "Alice".
Kotlin
Hint
Do not add ? after String because this variable cannot be null.
3
Use safe call and Elvis operator to handle null phone number
Create a variable called displayNumber that uses phoneNumber?.length to get the length safely, and if phoneNumber is null, use ?: to set displayNumber to "No number".
Kotlin
Hint
Use ?. to safely access length and ?: to provide a default value.
4
Print the contact name and phone number info
Write a println statement to print "Contact: " plus contactName and " - Phone length: " plus displayNumber.
Kotlin
Hint
Use string templates with $contactName and $displayNumber inside println.
Practice
(1/5)
1. What is the main purpose of Kotlin's null safety feature?
easy
A. To allow all variables to be null by default
B. To prevent errors caused by accessing null values
C. To make Kotlin code run faster
D. To remove the need for variable declarations
Solution
Step 1: Understand null safety concept
Kotlin's null safety is designed to avoid null pointer exceptions by making null handling explicit.
Step 2: Identify the main purpose
The main goal is to prevent errors caused by accessing null values, which are common bugs in many languages.
Final Answer:
To prevent errors caused by accessing null values -> Option B
Quick Check:
Null safety = prevent null errors [OK]
Hint: Null safety means avoiding null errors in code [OK]
Common Mistakes:
Thinking null safety allows all variables to be null
Believing it improves performance directly
Confusing null safety with removing declarations
2. Which of the following is the correct way to declare a nullable variable in Kotlin?
easy
A. val name: String? = null
B. val name: String = null
C. val name: String! = null
D. val name: String = ?null
Solution
Step 1: Recall Kotlin nullable syntax
In Kotlin, adding a question mark after the type makes it nullable, allowing it to hold null.
Step 2: Check each option
val name: String? = null uses String? which is correct. Others are invalid syntax or do not allow null.
Final Answer:
val name: String? = null -> Option A
Quick Check:
Nullable type uses ? after type [OK]
Hint: Use ? after type to allow nulls in Kotlin [OK]
Common Mistakes:
Omitting the ? for nullable types
Using invalid symbols like ! or ?null
Assigning null to non-nullable types
3. What will be the output of this Kotlin code?
val name: String? = null
println(name?.length ?: "No name")
medium
A. Throws NullPointerException
B. 0
C. null
D. No name
Solution
Step 1: Understand safe call and Elvis operator
The safe call ?. returns null if name is null. The Elvis operator ?: provides a default value if the left side is null.
Step 2: Evaluate the expression
Since name is null, name?.length is null, so the expression returns "No name".
4. Identify the error in this Kotlin code snippet:
val length = name.length
val name: String? = null
medium
A. Variable 'name' is used before declaration
B. No error, code runs fine
C. Missing semicolon after declaration
D. Cannot access length on nullable variable without safe call
Solution
Step 1: Analyze variable usage order
The variable name is used before it is declared.
Step 2: Identify the compile error
Kotlin requires variables to be declared before use, causing an unresolved reference error.
Final Answer:
Variable 'name' is used before declaration -> Option A
Quick Check:
Declare before use [OK]
Hint: Declare variables before using them in Kotlin [OK]
Common Mistakes:
Thinking it's only a null safety issue
Believing the code runs fine
Assuming Kotlin requires semicolons
5. How can you safely call a function printLength that prints the length of a nullable String text without causing a NullPointerException?
hard
A. fun printLength(text: String) { println(text.length) }
printLength(null)
B. fun printLength(text: String?) { println(text.length) }
printLength(null)
C. fun printLength(text: String?) { println(text?.length ?: 0) }
printLength(null)
D. fun printLength(text: String) { println(text?.length) }
printLength(null)
Solution
Step 1: Understand function parameter nullability
To accept null, parameter must be String?. Options A and D use non-nullable String, so passing null causes error.
Step 2: Use safe call and default value
fun printLength(text: String?) { println(text?.length ?: 0) }
printLength(null) uses safe call ?. and Elvis operator ?: to print 0 if text is null, avoiding exceptions.
Final Answer:
fun printLength(text: String?) { println(text?.length ?: 0) }
printLength(null) -> Option C
Quick Check:
Safe call + Elvis handles null safely [OK]
Hint: Use ?. and ?: to safely handle nullable parameters [OK]
Common Mistakes:
Passing null to non-nullable parameter
Accessing length without safe call
Ignoring default value for null case
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.