Skip to Content
Course content

26: Extension Functions

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 the Double type.
  • The function should return a String.
  • The output must prepend a dollar sign ($) and ensure exactly two decimal places are shown (Hint: use String.format("%.2f", this)).
  • Test it by calling 15.0.toCurrency() and 12.3456.toCurrency() to ensure the rounding and formatting work as expected.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.