
Extension in Kotlin
📌 Extensions in Kotlin
Extensions in Kotlin allow you to add new functionality to existing classes without modifying their source code. You can add methods or properties to classes using extensions.
This is particularly useful when working with third-party libraries or classes you don't own.
✅ 1. Extension Functions
An extension function allows you to add a new function to an existing class.
The syntax is:
fun ClassName.(): ReturnType { // Function body}
📌 Example:
fun String.(): String { return this.replace(" ", "")}fun () { val str = "Hello Kotlin Extensions" println(str.removeSpaces()) // Output: HelloKotlinExtensions}
🔎 Explanation:
this
refers to the object the function is called on (String
in this case).The function
removeSpaces()
removes all spaces usingreplace()
.
✅ 2. Extension Properties
You can also add properties using extensions.
Note that extension properties cannot store state — they rely on getters.
📌 Example:
val String.wordCount: Int get() = this.split(" ").sizefun () { val sentence = "Kotlin is a concise language" println("Word Count: ${sentence.wordCount}") fun String?.(): Boolean { return this == null || this.isEmpty()}fun () { val str: String? = null println(str.isNullOrEmpty()) // Output: true val str2: String? = "" println(str2.isNullOrEmpty()) // Output: true}
🔎 Explanation:
String?
indicates the function works with nullable strings.It checks for both
null
and empty values.
✅ 4. Extension Functions with Inheritance
Extension functions are not overridden if a subclass has the same function.
📌 Example:
open class Animalclass Dog : Animal()fun Animal.() = println("Animal makes a sound")fun Dog.() = println("Dog barks")fun () { val animal: Animal = Dog() animal.sound() // Output: Animal makes a sound}
🔎 Explanation:
Kotlin chooses the extension based on the reference type (
Animal
) instead of the actual object (Dog
).
✅ 5. Using Extensions with Companion Objects
You can extend a companion object using extensions.
📌 Example:
class MathUtils { companion object {}}fun MathUtils.Companion.(num: Int): fun main() { println(MathUtils.square(4)) // Output: 16}
🔎 Explanation:
MathUtils.Companion
is extended to add asquare()
function.
✅ 6. Conclusion
Extension Functions → Add new functions to classes without modifying them.
Extension Properties → Provide calculated properties using getters.
Nullable Extensions → Handle null safely with extension functions.
Extensions with Inheritance → Work based on reference type, not actual object.
Companion Object Extensions → Extend companion objects for utility functions.