When developing Android applications, we frequently work with data that may not always be available.
For example:
- A user may not have uploaded a profile picture.
- An API response may contain missing fields.
- A database query may return no result.
- A user may leave an optional input field empty.
- A device location may not be available.
- A user account may not contain a display name.
In programming, the absence of a value is often represented using null.
However, accessing properties or calling methods on null values can cause runtime errors.
Kotlin provides a powerful null safety system that helps developers handle nullable values safely and reduce NullPointerExceptions.
In this tutorial, we’ll explore Kotlin null safety from beginner to intermediate level, including nullable types, safe calls, the Elvis operator, the let function, safe casts, and practical Jetpack Compose examples.
What You’ll Learn
By the end of this tutorial, you’ll understand:
- What null means in Kotlin
- Why null safety is important
- Nullable and non-nullable types
- Safe call operator
?. - Elvis operator
?: - Not-null assertion operator
!! - Smart casts
- Safe casts using
as? - The
letscope function - Safe call chaining
- Nullable function parameters
- Nullable return types
- Null safety in Android applications
- Null handling in Jetpack Compose
- Common null safety mistakes
- Practical Kotlin exercises
Let’s begin!
1. What Is Null in Kotlin?
In Kotlin, null represents the absence of a value.
Consider a user profile application.
A user may have a name but may not have provided a phone number.
val username = "Alex"
val phoneNumber: String? = null
Here:
usernamecontains a String value.phoneNumbercontains null.- The
?symbol indicates that the variable can hold null.
Kotlin distinguishes between nullable and non-nullable types.
This distinction is one of Kotlin’s most important language features.
2. Why Is Null Safety Important?
In many programming languages, accessing a null reference can cause a runtime exception.
For example, consider attempting to access the length of a missing username.
val username: String? = null
If we try to access:
println(username.length)
Kotlin reports a compile-time error because username may be null.
This helps prevent unsafe access before the application runs.
Benefits of Kotlin Null Safety
- Reduces accidental NullPointerExceptions.
- Makes nullable values explicit.
- Encourages safer API handling.
- Improves code readability.
- Helps identify potential problems during compilation.
- Supports safer Android application development.
Kotlin’s null safety reduces many common errors, although NullPointerExceptions can still occur through unsafe assertions, Java interoperability, or other runtime situations.
3. Kotlin Non-Nullable Types
By default, Kotlin variables cannot contain null.
Example
val name: String = "Alex"
This variable must contain a non-null String value.
The following code is invalid:
val name: String = null
Kotlin reports a type mismatch because null cannot be assigned to a non-nullable String.
Another Example
val age: Int = 25
println(age)
Output:
25
Non-nullable types make it easier to work with values that are guaranteed to be present within Kotlin’s type system.
4. Kotlin Nullable Types
To allow a variable to contain null, add ? after the type.
Syntax
var variableName: DataType? = null
Example
var username: String? = null
username = "Alex"
println(username)
Output:
Alex
Nullable Integer
var age: Int? = null
age = 30
println(age)
Output:
30
Nullable Boolean
val isPremium: Boolean? = null
A nullable Boolean can contain:
truefalsenull
This is different from a regular Boolean, which can contain only true or false.
5. Checking Null Using if-else
The simplest way to handle a nullable value is to check whether it is null.
Example
fun main() {
val username: String? = "Alex"
if (username != null) {
println(username.length)
} else {
println("Username is missing")
}
}
Output:
4
How It Works
The condition:
username != null
checks whether the value exists.
Inside the true branch, Kotlin can treat the stable local variable as non-null.
This behavior is called a smart cast.
6. Kotlin Smart Casts
Kotlin can automatically recognize when a value has been checked and safely use it as a more specific type.
Example
fun main() {
val message: String? = "Hello Kotlin"
if (message != null) {
println(message.uppercase())
}
}
Output:
HELLO KOTLIN
After the null check, Kotlin knows that message is not null inside the branch.
Important
Smart casts are available only when Kotlin can establish that the value cannot change unexpectedly between the check and its use.
For example, mutable properties that can change externally may not be eligible for smart casting.
7. Kotlin Safe Call Operator (?.)
Kotlin provides the safe call operator to access properties or call functions on nullable values.
Syntax
nullableVariable?.property
Example
fun main() {
val username: String? = null
println(username?.length)
}
Output:
null
How It Works
If username contains a value, Kotlin accesses its length.
If username is null, the expression returns null instead of throwing an exception.
Another Example
val username: String? = "Android"
println(username?.uppercase())
Output:
ANDROID
Safe calls are commonly used when handling optional values in Android applications.
8. Kotlin Elvis Operator (?:)
The Elvis operator provides a fallback value when an expression evaluates to null.
Syntax
nullableValue ?: defaultValue
Example
fun main() {
val username: String? = null
val displayName = username ?: "Guest"
println(displayName)
}
Output:
Guest
Another Example
val username: String? = "Alex"
val displayName = username ?: "Guest"
println(displayName)
Output:
Alex
Practical Android Example
val profileImageUrl: String? = null
val imageUrl = profileImageUrl ?: "default_profile.png"
println(imageUrl)
Output:
default_profile.png
The Elvis operator is useful for displaying default values when optional data is missing.
9. Combining Safe Calls and Elvis Operator
Safe calls and the Elvis operator are frequently used together.
Example
fun main() {
val username: String? = null
val length = username?.length ?: 0
println(length)
}
Output:
0
Explanation
First:
username?.length
tries to retrieve the length safely.
If the result is null:
?: 0
provides zero as the fallback.
Another Example
val email: String? = null
val displayEmail = email?.lowercase() ?: "No Email"
println(displayEmail)
Output:
No Email
This combination makes nullable value handling concise and readable.
10. Kotlin Not-Null Assertion Operator (!!)
Kotlin provides the not-null assertion operator:
!!
It tells Kotlin to treat a nullable value as non-null.
Example
val username: String? = "Alex"
println(username!!.length)
Output:
4
However, this operator can be dangerous.
Unsafe Example
val username: String? = null
println(username!!.length)
Result:
NullPointerException
Best Practice
Avoid using !! unless you have a strong, justified guarantee that the value cannot be null.
Prefer:
username?.length
or:
username?.length ?: 0
Safe calls and explicit validation generally make code more reliable.
11. Kotlin let Function with Nullable Values
Kotlin provides the let scope function.
When combined with a safe call, let allows us to execute code only when a nullable value is not null.
Example
fun main() {
val username: String? = "Alex"
username?.let { name ->
println("Welcome, $name")
}
}
Output:
Welcome, Alex
How It Works
The expression:
username?.let { name ->
println(name)
}
executes the lambda only if username is not null.
Inside the lambda, name is non-null.
Another Example
val email: String? = null
email?.let {
println("Email: $it")
}
Because email is null, the lambda is not executed.
Practical Uses
The let function is useful for:
- Processing optional user information.
- Working with nullable API values.
- Handling optional database results.
- Executing code only when a value exists.
Remember that let itself is not a null-checking function; the safe call ?. is what prevents the lambda from executing for null.
12. Kotlin Safe Call Chaining
Sometimes we need to access nested properties.
Consider the following data classes:
data class Address(
val city: String?
)
data class User(
val name: String,
val address: Address?
)
Example
fun main() {
val user = User(
name = "Alex",
address = null
)
val city = user.address?.city ?: "Unknown City"
println(city)
}
Output:
Unknown City
Multiple Safe Calls
If the user itself can be null:
val user: User? = null
val city = user?.address?.city ?: "Unknown City"
println(city)
Output:
Unknown City
Safe call chaining is useful when working with nested API responses and optional model properties.
13. Kotlin Safe Cast Operator (as?)
Kotlin provides the safe cast operator:
as?
It attempts to cast a value to another type.
If the cast is not possible, it returns null.
Example
fun main() {
val value: Any = "Hello Kotlin"
val text: String? = value as? String
println(text)
}
Output:
Hello Kotlin
Failed Cast Example
val value: Any = 100
val text: String? = value as? String
println(text)
Output:
null
Why Use Safe Casts?
A regular unsafe cast may throw an exception if the value is not compatible with the requested type.
Safe casts help avoid that exception by returning null.
14. Nullable Function Parameters
Functions can accept nullable parameters.
Example
fun greetUser(name: String?) {
val displayName = name ?: "Guest"
println("Hello, $displayName")
}
fun main() {
greetUser("Alex")
greetUser(null)
}
Output:
Hello, Alex
Hello, Guest
Practical Example
fun formatPhoneNumber(phone: String?): String {
return phone ?: "Phone number not available"
}
Usage
println(formatPhoneNumber(null))
Output:
Phone number not available
Nullable parameters are useful when functions accept optional information.
15. Nullable Function Return Types
Functions can also return null.
Example
fun findUser(id: Int): String? {
return if (id == 1) {
"Alex"
} else {
null
}
}
Usage
fun main() {
val username = findUser(2)
println(username ?: "User Not Found")
}
Output:
User Not Found
Android Use Cases
Nullable return types are common when:
- A database record is missing.
- A search produces no match.
- An optional preference is unavailable.
- A user profile field is absent.
They make the possibility of missing data explicit.
16. Kotlin Null Safety with Collections
Kotlin collections can contain nullable elements.
Example
val usernames: List<String?> = listOf(
"Alex",
null,
"Emma",
null,
"John"
)
Using a Loop
for (username in usernames) {
println(username ?: "Unknown User")
}
Output:
Alex
Unknown User
Emma
Unknown User
John
Using filterNotNull()
Kotlin provides the filterNotNull() function.
val validUsers = usernames.filterNotNull()
println(validUsers)
Output:
[Alex, Emma, John]
This creates a list containing only non-null elements.
Important Difference
These types are not the same:
List<String?>
A non-null list that may contain null elements.
List<String>?
A nullable list whose elements are non-null Strings.
List<String?>?
A nullable list that may also contain null elements.
Understanding these differences is important when working with API and database models.
17. Practical Android Example: User Profile Data
Let’s create a simple user profile model.
data class UserProfile(
val name: String,
val email: String?,
val phone: String?,
val city: String?
)
Create User Data
val user = UserProfile(
name = "Alex",
email = "alex@example.com",
phone = null,
city = null
)
Display Profile Information
fun displayUserProfile(user: UserProfile) {
println("Name: ${user.name}")
println(
"Email: ${user.email ?: "Not Available"}"
)
println(
"Phone: ${user.phone ?: "Not Available"}"
)
println(
"City: ${user.city ?: "Not Available"}"
)
}
Usage
fun main() {
val user = UserProfile(
name = "Alex",
email = "alex@example.com",
phone = null,
city = null
)
displayUserProfile(user)
}
Output:
Name: Alex
Email: alex@example.com
Phone: Not Available
City: Not Available
Why Is This Useful?
Real applications often receive incomplete user profile information.
Nullable properties allow us to represent missing data without inventing placeholder values in the model.
The UI can then decide how to display missing fields.
18. Kotlin Null Safety in Jetpack Compose
Jetpack Compose applications frequently display data that may be nullable.
For example, a user’s display name may be missing.
Let’s create a reusable Compose profile card that safely handles optional values.
Step 1: Create the Data Model
data class ProfileUiModel(
val name: String?,
val email: String?,
val city: String?
)
Step 2: Create the Composable Function
@Composable
fun NullableProfileCard(
profile: ProfileUiModel?
) {
Card(
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier.padding(20.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Text(
text = profile?.name ?: "Guest User",
style = MaterialTheme.typography.titleLarge
)
Text(
text = profile?.email ?: "Email not available",
style = MaterialTheme.typography.bodyMedium
)
Text(
text = profile?.city ?: "Location not available",
style = MaterialTheme.typography.bodyMedium
)
}
}
}
Step 3: Create the Screen
@Composable
fun NullSafetyDemoScreen() {
val profile = ProfileUiModel(
name = "Alex",
email = null,
city = "Hyderabad"
)
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
Text(
text = "Kotlin Null Safety Demo",
style = MaterialTheme.typography.headlineSmall
)
NullableProfileCard(
profile = profile
)
}
}
Required Imports
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
Expected UI
+--------------------------------+
| |
| Kotlin Null Safety Demo |
| |
| +----------------------------+ |
| | | |
| | Alex | |
| | | |
| | Email not available | |
| | | |
| | Hyderabad | |
| | | |
| +----------------------------+ |
| |
+--------------------------------+
How It Works
The profile parameter is nullable:
profile: ProfileUiModel?
This means the entire profile may be missing.
The safe call operator:
profile?.name
accesses the name only when the profile exists.
The Elvis operator:
?: "Guest User"
provides a fallback value.
This prevents unsafe nullable property access and allows the UI to display meaningful information.
19. Jetpack Compose Example: Nullable State
In real Android applications, UI data may initially be null while information is being loaded.
Let’s create a simple demonstration.
@Composable
fun UserNameScreen() {
var username by remember {
mutableStateOf<String?>(null)
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(24.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = username ?: "No User Selected",
style = MaterialTheme.typography.headlineSmall
)
Spacer(
modifier = Modifier.height(20.dp)
)
Button(
onClick = {
username = "Alex"
}
) {
Text("Load User")
}
Spacer(
modifier = Modifier.height(12.dp)
)
Button(
onClick = {
username = null
}
) {
Text("Clear User")
}
}
}
Required Imports
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
Initial UI
+--------------------------------+
| |
| No User Selected |
| |
| [Load User] |
| |
| [Clear User] |
| |
+--------------------------------+
After Tapping Load User
+--------------------------------+
| |
| Alex |
| |
| [Load User] |
| |
| [Clear User] |
| |
+--------------------------------+
Explanation
The state variable:
var username by remember {
mutableStateOf<String?>(null)
}
can contain either a String or null.
When the button updates the state, Jetpack Compose recomposes the relevant UI.
The Elvis operator determines what text appears.
This is a simplified demonstration. Production applications often model loading, success, and error states separately rather than using null to represent every state.
20. Common Kotlin Null Safety Mistakes
Mistake 1: Assigning Null to a Non-Nullable Type
Incorrect:
val username: String = null
Correct:
val username: String? = null
Use nullable types only when null is a valid possibility.
Mistake 2: Accessing Nullable Properties Directly
Incorrect:
val username: String? = null
println(username.length)
Correct:
println(username?.length)
Or:
println(username?.length ?: 0)
Mistake 3: Overusing the !! Operator
Avoid:
val username: String? = null
println(username!!.length)
Prefer safe calls or explicit validation.
Mistake 4: Confusing Null and Empty Strings
These values are different:
val first: String? = null
val second: String = ""
The first represents an absent value.
The second represents an existing String containing no characters.
If your application needs to handle both cases, consider:
val displayName = username
?.takeIf { it.isNotBlank() }
?: "Guest"
This uses "Guest" when the username is null, empty, or contains only whitespace.
Mistake 5: Using Null for Every UI State
Avoid using a nullable value as the only representation of loading, success, and error states.
A null result might mean several different things.
For more complex Android applications, use explicit UI state models.
For example:
sealed interface UserUiState {
data object Loading : UserUiState
data class Success(
val username: String
) : UserUiState
data class Error(
val message: String
) : UserUiState
}
This makes each application state explicit.
We’ll explore sealed types and UI state management in future tutorials.
21. Kotlin Null Safety Best Practices
Follow these recommendations when working with nullable values.
Prefer Non-Nullable Types
Use non-nullable types whenever the value must always exist.
Use Safe Calls
Prefer:
user?.name
instead of unsafe assertions.
Provide Meaningful Fallback Values
Use the Elvis operator when a default value makes sense.
val displayName = name ?: "Guest"
Validate Required Data
Don’t silently replace null when the value is required for an important operation.
For example, a missing payment amount should be treated as a validation error rather than automatically replaced with zero.
Avoid Unnecessary Nullability
Don’t make every property nullable.
Design your data models according to actual business requirements.
Use Explicit UI States
In production Android applications, represent loading, success, and error states clearly.
22. Kotlin Null Safety Quick Reference
| Concept | Syntax | Purpose |
|---|---|---|
| Nullable type | String? | Allows null |
| Non-nullable type | String | Disallows null in normal Kotlin assignments |
| Null check | value != null | Checks value availability |
| Safe call | value?.length | Safely accesses a member |
| Elvis operator | value ?: default | Provides fallback |
| Not-null assertion | value!! | Asserts non-null; may throw |
| Safe cast | value as? String | Returns null if cast fails |
| Safe let | value?.let { } | Executes lambda for non-null value |
| Safe chaining | user?.address?.city | Handles nested nullable values |
| Nullable return | fun getUser(): User? | Allows function to return null |
| Filter nulls | list.filterNotNull() | Removes null elements |
23. Practical Exercises
Try these exercises to improve your Kotlin null safety skills.
Exercise 1: Nullable Username
Create a nullable username variable.
If the username is null, display "Guest".
Otherwise, display the actual username.
Exercise 2: Safe String Length
Create a nullable String.
Use the safe call and Elvis operators to return its length or zero.
Exercise 3: Nullable Function
Create a function:
fun getUserName(id: Int): String?
Return a username for a valid ID and null for an invalid ID.
Exercise 4: Safe Cast
Create a variable of type Any.
Attempt to cast it to String using as?.
Handle a failed cast safely.
Exercise 5: Nullable List
Create a list containing nullable Strings.
Use filterNotNull() to remove null values.
Exercise 6: Jetpack Compose Profile Screen
Create a profile screen that displays:
- Username
- Phone number
- City
Allow some properties to be nullable.
Display meaningful fallback text when data is missing.
What We’ve Learned
In this tutorial, we learned:
- What null represents in Kotlin
- Why null safety matters
- Nullable and non-nullable types
- Explicit null checks
- Smart casts
- Safe call operator
- Elvis operator
- Not-null assertion operator
- The
letscope function - Safe call chaining
- Safe casts
- Nullable function parameters
- Nullable return types
- Nullable collections
- Practical Android profile models
- Null handling in Jetpack Compose
- Common null safety mistakes
- Kotlin null safety best practices
Kotlin null safety is an essential feature for writing reliable and maintainable Android applications.
By using nullable types, safe calls, and appropriate fallback handling, we can prevent many common runtime errors and make our code easier to understand.
What’s Next?
In our next tutorial, we’ll explore:
Kotlin Classes and Objects Explained: Constructors, Properties & Methods
You’ll learn:
- What classes and objects are
- Creating Kotlin classes
- Primary constructors
- Secondary constructors
- Class properties
- Member functions
- The
initblock - Visibility modifiers
- Practical Android examples
- Using classes with Jetpack Compose
Happy Coding!
Continue learning modern Android development with Moiks Developer Blog.