0
0
Kotlinprogramming~3 mins

Why Extensions resolved statically in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could add new powers to any class without opening its code, but still keep everything clear and safe?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
fun printInfo(obj: MyClass) { println(obj.info()) }
After
fun MyClass.printInfo() { println(this.info()) }
What It Enables

This lets you add useful functions to existing classes cleanly, making your code easier to read and maintain without changing original class code.

Real Life Example

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.

Key Takeaways

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.