0
0
Kotlinprogramming~15 mins

Extensions vs member functions priority in Kotlin - Hands-On Comparison

Choose your learning style9 modes available
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
1
Create the Device class with a member function
Create a class called Device with a member function status() that returns the string "Member function status".
Kotlin
Need a hint?

Define a class named Device. Inside it, write a function status that returns the exact string "Member function status".

2
Add an extension function status() for Device
Create an extension function called status() for the Device class that returns the string "Extension function status".
Kotlin
Need a hint?

Write a function outside the class with the syntax fun Device.status(): String. It should return "Extension function status".

3
Create an instance of Device called device
Create a variable called device and assign it a new instance of the Device class.
Kotlin
Need a hint?

Use val device = Device() to create the instance.

4
Call device.status() and print the result
Call the status() function on the device instance and print the returned string using println.
Kotlin
Need a hint?

Use println(device.status()) to print the output. Notice which function is called.