Extension functions add methods to existing types without inheritance or wrapper classes—resolved statically at compile time. They power Kotlin stdlib conveniences like String.trimIndent().
Declaring extensions
fun String.wordCount(): Int =
trim().split(Regex("\s+")).size
Extensions do not modify the original class bytecode; they are syntactic sugar calling static helpers with the receiver as the first argument.
Guidelines
- Prefer extensions for domain-specific helpers on types you do not own
- Avoid hiding member functions—extensions never override members
- Keep extensions close to their domain package
Important interview questions and answers
- Q: Do extensions add fields?
A: No—only methods; state still lives in the receiver or wrappers. - Q: Static resolution?
A: The extension called depends on the declared static type, not runtime subtype—unlike virtual methods.
Self-check
- What keyword introduces the receiver type?
- Can extensions override class methods?
Pitfall: Extensions do not add members to the class—they are static helpers resolved at compile time.
Interview prep
- Do extensions modify classes?
No—compile-time syntactic sugar on receiver type.
- When to use?
Adapt third-party APIs without subclassing.