Lately, I’ve been diving into the Kotlin book “Atom Kotlin,” and I find the concept of extension functions truly remarkable. Despite being a small feature, when leveraged effectively, it has the potential to bring about significant improvements in your code.
Syntax of the extension function
Imagine you want to add single and double quote methods to strings. With extensions, it’s a breeze:
fun String.doubleQuote() = “”this””
Now you can use these functions like they were always part of the String class:
Combo power: Chaining extensions
Need to apply multiple extensions one after another? No sweat! Just keep using the this keyword to reference the modified string. Like this:
Simplifying Class Functionality
Extensions aren’t just for other people’s code. You can use them to improve your own classes too! Let’s say you have a Book class:
With an extension, you can easily categorize books:
“””title: “$title”, category: $category”””
Now you can categorize books without writing out the title property every time.
Things to keep in mind:
Extensions can only access public parts of the class they’re extending.
They’re a kind of syntactic magic, making your code look cleaner and more natural.
Final thought
In short, extension functions are a powerful tool in Kotlin that lets you add functionality and improve code readability. It’s like giving your code superpowers!
Refs: Atomic Kotlin by Bruce Eckel , Svetlana Isakova