Extensions vs member functions priority
📖 Scenario: Imagine you have a class representing a simple device. You want to add a function to show its status. Kotlin allows you to add functions directly inside the class or add extension functions outside the class. But what happens if both have the same function name?
🎯 Goal: You will create a class with a member function and an extension function with the same name. Then you will call the function to see which one Kotlin uses by default.
📋 What You'll Learn
Create a class called
Device with a member function status() that returns the string "Member function status".Create an extension function
status() for the Device class that returns the string "Extension function status".Create an instance of
Device called device.Call
device.status() and print the result.💡 Why This Matters
🌍 Real World
In real apps, you might want to add new functions to existing classes without changing their code. Kotlin extensions let you do that, but member functions always take priority if they exist.
💼 Career
Understanding how Kotlin resolves functions helps you avoid bugs and write clearer code, which is important for Android development and other Kotlin-based projects.
Progress0 / 4 steps