0
0
Kotlinprogramming~15 mins

Nullable receiver extensions in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Nullable Receiver Extensions
📖 Scenario: Imagine you are building a simple app that processes user comments. Sometimes, the comment text might be missing (null). You want to safely check if a comment is empty or not, even if the comment itself is null.
🎯 Goal: Create a Kotlin extension function with a nullable receiver that checks if a string is null or empty. Then use it to safely check comments.
📋 What You'll Learn
Create a nullable receiver extension function called isNullOrEmptyCustom for String?
The function should return true if the string is null or empty, otherwise false
Create a list of nullable strings called comments with exact values: "Hello", "", null, "Kotlin"
Use a for loop with variables comment to iterate over comments
Inside the loop, print "Empty or null" if comment.isNullOrEmptyCustom() is true, else print the comment text
💡 Why This Matters
🌍 Real World
Nullable receiver extensions help safely add functions to types that can be null, avoiding crashes and making code cleaner.
💼 Career
Understanding nullable receiver extensions is important for Kotlin developers to write safe and readable code, especially when dealing with optional data.
Progress0 / 4 steps
1
Create the list of nullable comments
Create a list called comments with these exact nullable string values: "Hello", "", null, "Kotlin"
Kotlin
Need a hint?

Use listOf to create a list with nullable strings.

2
Create the nullable receiver extension function
Create an extension function called isNullOrEmptyCustom with a nullable String? receiver that returns true if the string is null or empty, otherwise false
Kotlin
Need a hint?

Use fun String?.isNullOrEmptyCustom() to define the extension function with nullable receiver.

3
Use a for loop to check each comment
Use a for loop with variable comment to iterate over comments. Inside the loop, use comment.isNullOrEmptyCustom() to check if the comment is empty or null.
Kotlin
Need a hint?

Use for (comment in comments) to loop, then if (comment.isNullOrEmptyCustom()) to check.

4
Print the results
Print the output inside the loop as specified: print "Empty or null" if comment.isNullOrEmptyCustom() is true, otherwise print the comment text.
Kotlin
Need a hint?

Use println to print the correct output inside the loop.