0
0
Kotlinprogramming~3 mins

Extensions vs member functions priority in Kotlin - When to Use Which

Choose your learning style9 modes available
The Big Idea

What if your new function never runs because the original one silently takes priority?

The Scenario

Imagine you have a class with some functions, and you want to add new behavior without changing the original class code. You try to add extra functions outside the class, but sometimes the program doesn't use your new functions as you expected.

The Problem

Manually guessing which function will run--your added one or the original--can be confusing and cause bugs. You might waste time debugging why your new code is ignored, especially when both have the same name.

The Solution

Kotlin's rule that member functions always have priority over extension functions clears this confusion. It helps you know exactly which function will run, making your code predictable and easier to maintain.

Before vs After
Before
fun String.print() { println("Extension") }
class Example { fun print() { println("Member") } }
Example().print()
After
class Example { fun print() { println("Member") } }
fun Example.print() { println("Extension") }
Example().print()
What It Enables

This rule lets you safely add new functions to classes without accidentally overriding existing behavior, making your code clearer and more reliable.

Real Life Example

When working with a library class you cannot change, you can add helpful functions as extensions. Knowing member functions have priority prevents unexpected behavior when the library updates its own functions.

Key Takeaways

Member functions always run before extension functions if both have the same name.

This rule avoids confusion and bugs when adding new functions to existing classes.

It helps keep your code predictable and easier to maintain.