Problem Statement
How do you create extension functions and what are their limitations and best practices?
Explanation
Create extension functions by prefixing the function name with the receiver type followed by a dot like fun String dot reverse open paren close paren colon String equals this dot reversed open paren close paren, where this refers to the receiver object. Extension functions are resolved statically based on the declared type not the runtime type, meaning they don't support polymorphism, and they cannot access private or protected members of the class they extend only public members.
Use extension functions to add utility methods to classes you don't own, create domain-specific APIs without modifying original classes, and organize related utility functions near the types they work with rather than in separate util classes. Be careful not to pollute the namespace with too many extensions, and prefer member functions when you need access to private state or virtual dispatch.
Best practices include keeping extensions focused and cohesive, organizing them in files grouped by the types they extend, documenting extensions well since they appear like member functions but have different access rules, and considering making extensions private or internal to limit their scope. Extension functions are powerful but should be used thoughtfully to maintain code clarity.
