Kotlin Tip #7: Make use of Extension Functions — 100 Kotlin Tips in 100 Days

Raphael De Lio
Kotlin with Raphael De Lio
2 min readFeb 16, 2024

Twitter | LinkedIn | YouTube | Instagram
Tip #6: Explore Range Expressions with ‘..’

In the old Java days, we relied on utility classes to extend the functionality of classes that cannot be modified, like the String class. An example of these utility classes is the Apache Commons' StringUtils. If you ever needed to use this approach, you've probably quickly realized how much it tends to clutter our codebase, making the code more difficult to reason and navigate.

That's why extension functions are one of my favorite Kotlin features. As their name suggests, they allow you to extend, or “attach”, new functions to existing classes.

Let’s say you often find yourself needing to check if a string is a valid email address in your Kotlin applications. Normally, you might write a utility function that takes a string as input. With extension functions, you can make this check feel like a natural part of the String class:

In this example, isValidEmail is an extension function on the String class, making the code intuitive and clean.

Extension functions shine not just with Kotlin’s standard library classes but also with custom classes. Imagine you have a UserProfile class coming from an external library, and you want to add a method to serialize it to JSON format:

As you get more comfortable with extension functions, you can start tackling more complex scenarios. For instance, you might extend collections with custom filtering logic:

In this example, transformFirstMatch searches through the products list to find the first product that's on sale. Once it finds such a product (Smartphone in this case), it applies a 10% discount to the price and returns the discounted price. If no products were on sale, it would return null.

Extension functions show how Kotlin, once again, enables developers to write more concise, clean, and expressive code. Making the whole development process more productive and enjoyable.

I hope you have enjoyed the seventh tip of our series! Don’t forget to subscribe and stay tuned for more Kotlin tips!

Stay curious!

Tip #8: Embrace Single Expression Functions

Contribute

Writing takes time and effort. I love writing and sharing knowledge, but I also have bills to pay. If you like my work, please, consider donating through Buy Me a Coffee: https://www.buymeacoffee.com/RaphaelDeLio

Or by sending me BitCoin: 1HjG7pmghg3Z8RATH4aiUWr156BGafJ6Zw

Follow Me on Social Media

Stay connected and dive deeper into the world of Kotlin with me! Follow my journey across all major social platforms for exclusive content, tips, and discussions.

Twitter | LinkedIn | YouTube | Instagram

--

--