Kotlin Extension Function
In Kotlin, an extension function is a way to add new functionality to an existing class without having to inherit from it or modify its source code. Extension functions allow you to extend the behavior of a class by adding new functions that can be called as if they were part of the original class.
To define an extension function, you need to prefix the function name with the name of the class you want to extend, followed by a dot (.
). The first parameter of the function should be the object that you want to extend. Here's an example:
fun String.toTitleCase(): String { return split(" ").joinToString(" ") { it.capitalize() } }
In this example, we define an extension function called toTitleCase()
for the String
class. This function takes a string and returns a new string with the first letter of each word capitalized.
Once you have defined an extension function, you can use it just like any other member function of the class it extends:
val title = "the quick brown fox".toTitleCase() println(title) // prints "The Quick Brown Fox"
Extension functions can be defined for any class, including third-party libraries and built-in classes like String
, Int
, and List
. They can also be defined as members of a class, allowing you to create a domain-specific language (DSL) or provide a more fluent API for your classes.
One thing to keep in mind is that extension functions are not part of the original class and can't access its private members. They also can't be overridden, so if you define an extension function with the same name and signature as a member function of the class, the member function will always take precedence.