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