Kotlin: Extension functions

cuongnp

cuongnp

Posted on April 22, 2024

Kotlin: Extension functions

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

fun ReceiverType.extensionFunction() { ... }
Enter fullscreen mode Exit fullscreen mode
  • Imagine you want to add single and double quote methods to strings. With extensions, it's a breeze:
fun String.singleQuote() = "'$this'"
fun String.doubleQuote() = "\"this\""
Enter fullscreen mode Exit fullscreen mode
  • Now you can use these functions like they were always part of the String class:
"Hi".singleQuote() // Now "Hi" is in single quotes!
Enter fullscreen mode Exit fullscreen mode

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:

fun String.strangeQuote() = this.singleQuote().singleQuote() // Double the quotes!
Enter fullscreen mode Exit fullscreen mode

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:

class Book(val title: String)
Enter fullscreen mode Exit fullscreen mode

With an extension, you can easily categorize books:

fun Book.categorize(category: String) =
"""title: "$title", category: $category"""
Enter fullscreen mode Exit fullscreen mode

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

💖 💪 🙅 🚩
cuongnp
cuongnp

Posted on April 22, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Kotlin: Extension functions
beginners Kotlin: Extension functions

April 22, 2024