0
0
Kotlinprogramming~30 mins

Extensions resolved statically in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Extensions Resolved Statically in Kotlin
📖 Scenario: You are working on a Kotlin project where you want to add new functions to existing classes without changing their source code. Kotlin extensions let you do this, but they are resolved statically, which means the function called depends on the type of the variable, not the actual object it points to.Let's explore this behavior with a simple example.
🎯 Goal: Build a Kotlin program that shows how extension functions are resolved statically by creating two classes and extension functions for them, then calling these functions through variables of different types.
📋 What You'll Learn
Create two classes: Base and Derived where Derived inherits from Base.
Create an extension function printMessage() for Base that prints "Base extension".
Create an extension function printMessage() for Derived that prints "Derived extension".
Create a function showMessage() that takes a Base parameter and calls printMessage() on it.
Create a Derived object and call showMessage() passing it as a Base type.
Print the output to observe which extension function is called.
💡 Why This Matters
🌍 Real World
Extension functions let you add new features to existing classes without changing their code, useful when working with libraries or APIs you cannot modify.
💼 Career
Understanding how Kotlin resolves extension functions helps avoid bugs and write clearer, more predictable code in Android and Kotlin backend development.
Progress0 / 4 steps
1
Create classes Base and Derived
Create a class called Base and a class called Derived that inherits from Base.
Kotlin
Need a hint?

Use open keyword to allow inheritance for Base.

2
Create extension functions printMessage() for Base and Derived
Create an extension function called printMessage() for Base that prints "Base extension" and another extension function called printMessage() for Derived that prints "Derived extension".
Kotlin
Need a hint?

Define extension functions outside the classes using fun ClassName.functionName() syntax.

3
Create function showMessage() that calls printMessage()
Create a function called showMessage() that takes a parameter obj of type Base and calls obj.printMessage() inside it.
Kotlin
Need a hint?

Call the extension function on the parameter inside the function body.

4
Create a Derived object and call showMessage()
Create a variable called derivedObj of type Derived and assign it a new Derived() object. Then call showMessage(derivedObj) and print the output.
Kotlin
Need a hint?

Remember that extension functions are resolved by the variable type, not the actual object type.