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 falseCreate a list of nullable strings called
comments with exact values: "Hello", "", null, "Kotlin"Use a
for loop with variables comment to iterate over commentsInside 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