What if you could add new powers to any class without opening its code, but still keep everything clear and safe?
Why Extensions resolved statically in Kotlin? - Purpose & Use Cases
Imagine you have a class and you want to add new functions to it without changing its original code. You try to write new functions that look like they belong to the class, but you have to call them separately, which feels clumsy and confusing.
Manually calling extra functions outside the class makes your code messy and hard to read. You might forget to call them or mix up which function belongs where. It also becomes difficult to maintain and understand, especially when many such additions pile up.
Kotlin's extensions let you write new functions that look like they belong to the class, even though they are defined outside. But these extensions are resolved based on the type known at compile time, making the behavior predictable and clear.
fun printInfo(obj: MyClass) { println(obj.info()) }fun MyClass.printInfo() { println(this.info()) }This lets you add useful functions to existing classes cleanly, making your code easier to read and maintain without changing original class code.
Suppose you use a library class that you cannot modify. You want to add a function to format its data nicely. Extensions let you do this as if the function was part of the class, improving your app's code clarity.
Extensions add new functions to classes without modifying them.
They are resolved based on the variable's declared type, not runtime type.
This makes code cleaner and behavior predictable.