Quick Answer
Adding functionality to classes you don't own
Understanding the Issue
Extension functions allow adding new functions to existing classes without modifying their source code. They're resolved statically (based on the declared type) and don't actually modify the original class.
The Problem
This code demonstrates the issue:
Kotlin
Error
// Problem: Utility class
object StringUtils {
fun capitalize(s: String): String {
return s.replaceFirstChar { it.uppercase() }
}
}
The Solution
Here's the corrected code:
Kotlin
Fixed
// Solution: Extension function
fun String.capitalize(): String {
return this.replaceFirstChar { it.uppercase() }
}
// Usage:
val name = "alice".capitalize()
// Extension properties:
val String.isEmail get() = this.matches(Regex("^\S+@\S+\.\S+$"))
Key Takeaways
Use extensions to add utility functions in a more discoverable and natural way.