How do extension functions work in Kotlin?
sobes.tech AI
Answer from AI
Extension functions allow adding new functions to existing classes without inheritance or using decorators.
They are declared with a prefix indicating the type to be extended:
fun String.removeFirstChar(): String {
// this refers to the object of the extended type (String)
return this.substring(1)
}
When calling an extension function, the compiler transforms it into a static method, which takes the object of the extended type as the first argument:
// Calling an extension function
val original = "Hello"
val modified = original.removeFirstChar()
// The compiler roughly transforms the call to:
// val modified = StringExtensionsKt.removeFirstChar(original)
(where StringExtensionsKt is the name of the generated Kotlin class with static methods if the extension function is outside a class.)
Extension functions do not modify the class itself. They only provide syntactic sugar for calling static methods. They do not have access to private or protected members of the extended class.
The main advantage is more readable code, mimicking OOP, while avoiding inheritance issues.
Any classes can be extended, including standard libraries and Java classes. Extension functions can be members of another class, in which case they are only called within that class.
When resolving overloads and conflicts, member functions of the class are preferred over extension functions. If there are multiple extension functions with the same signature, the one declared locally (in the same scope) takes precedence.