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.
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()
Key Takeaways
Use extensions to add utility functions in a more discoverable way.