Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
26: Extension Functions
One of the things I love most about Kotlin is that it lets us "add" functionality to classes we don't own. Think about the String class. It's used everywhere, but there are always a few specific manipulations you find yourself doing over and over again in your specific project. In the old days (or in Java), you'd end up with a StringUtils class filled with static methods. It works, but it's clunky to write StringUtils.slugify(myTitle) every time.
Cleaning up article titles for URLs
Let's say we're building a blog. We have article titles like "Hello Kotlin World!" but we need them to be "slugs" for the URL, like "hello-kotlin-world". Instead of a utility class, I'm going to write an extension function. This allows me to call the logic directly on any string instance.
fun String.toSlug(): String {
return this.lowercase()
.replace(Regex("[^a-z0-9]"), "-")
.replace(Regex("-+"), "-")
.trim('-')
}
Notice the String. prefix. That's the magic part. Inside the function, this refers to the actual string instance the function is being called on. Now, instead of some awkward utility call, I can just do this:
val title = "Kotlin Extension Functions are Cool!"
val urlPath = title.toSlug() // Result: "kotlin-extension-functions-are-cool"
The "State" Trap
When I first started with extensions, I made a classic rookie mistake. I forgot that extension functions don't actually modify the class they are extending; they are essentially just static helpers that look like member functions. I tried to write a function to "clear" a string, thinking I could somehow mutate the original object.
// MY MISTAKE: I thought this would "reset" the string
fun String.clear() {
this = ""
}
The compiler immediately yelled at me. You can't assign a value to this. Why? Because String is immutable in Kotlin (and Java), and more importantly, extension functions are resolved statically. They don't have access to the private internals of the class, and they certainly can't replace the instance itself.
To fix this, I had to remember that an extension function must return a new value if it wants to "change" something. If I want a cleared version of a string, I just return an empty string—though in this specific case, it's probably a useless function. The lesson here: extensions are for calculating or transforming, not for mutating the state of the object they extend.
Handling Nulls with Nullable Receivers
Here is a pro tip that will save you a lot of ?. chains. Sometimes you have a string that might be null, and you still want to run your extension logic without the app crashing or requiring a null check every single time. You can make the receiver nullable.
Let's modify our slugger to handle nulls gracefully so we don't have to check for nulls in our UI code:
fun String?.toSlugOrEmpty(): String {
if (this == null) return ""
return this.lowercase()
.replace(Regex("[^a-z0-9]"), "-")
.trim('-')
}
By using String? instead of String, I can now call myNullableTitle.toSlugOrEmpty() even if myNullableTitle is null. It's a clean way to encapsulate "default" behavior for optional data.
📋 Practical Task
Build a Currency Formatter Extension
In a financial app, you often have Double values that need to be displayed as currency strings (e.g., 12.5 becomes "$12.50"). Instead of formatting this manually in every Fragment or Activity, create an extension function for the Double class.
Requirements:
- Create an extension function called
toCurrency()for theDoubletype. - The function should return a
String. - The output must prepend a dollar sign (
$) and ensure exactly two decimal places are shown (Hint: useString.format("%.2f", this)). - Test it by calling
15.0.toCurrency()and12.3456.toCurrency()to ensure the rounding and formatting work as expected.
There are no comments for now.