Extension functions and properties
Why it matters
- Extensions appear everywhere in Android code (
View.isVisiblefrom core-ktx, or your ownContext.dphelpers). Knowing they are static, not virtual, prevents subtle bugs when a subclass changes behaviour. - Interviewers ask whether an extension can access
privatemembers, whether it can be overridden, and what happens when a member and an extension share the same signature. Getting these wrong signals a shallow understanding of the type system. - Misusing an extension where a polymorphic method is needed causes runtime surprises: the call binds to the declared type, not the runtime type.
- Extension properties cannot have a backing field or an initializer. Developers who try to store per-instance state in one either get a compile error or work around it with shared global state.
The simple explanation
- You hand a stranger a printed card that says "call the building manager". The card (extension) is fixed; it always points to the same manager (static call site).
An extension function adds a new call syntax to a type without modifying it. The compiler rewrites receiver.ext() into a static call such as ExtKt.ext(receiver). The receiver is just the first parameter. Resolution is static: the compiler picks the extension based on the declared type of the receiver, not its runtime type.
Key rules:
| Aspect | Member function | Extension function |
|---|---|---|
| Dispatch | Virtual (runtime type) | Static (compile-time type) |
Access to private members | Yes | No |
Access to internal members | Yes | Yes, from the same module |
| Can be overridden | Yes (if open) | No |
| Backing field for property | Yes | Never |
| Can be generic / reified | Generic yes, reified only if inline | Generic yes, reified only if inline |
When a member and an extension have the same name and an applicable signature, the member wins. The compiler shows a warning that the extension is shadowed by a member, but the code compiles and the member runs. An extension with the same name but different parameter types is a normal overload and can be called.
Extension properties must define their value with an explicit getter (and a setter for var). They cannot have an initializer such as = 0, and field is not available, because the extension does not add any storage to the class. This is true at top level, inside an object, and everywhere else.
Because the call is static, if you declare fun Shape.name() and fun BigCircle.name(), a BigCircle stored in a val s: Shape still gets Shape.name(). The extension body can call virtual members like area(), so the inner call is polymorphic, but the choice of extension is not.
Notes
- Resolution is static. The compiler chooses the extension from the declared type of the receiver.
val s: Shape = circle; s.describe()picksShape.describe, not aCircle-specific extension. - An extension cannot access
privateorprotectedmembers of the class it extends. It can accessinternalmembers only when it is in the same module. - A member function shadows an extension with the same applicable signature. The member is called, and the compiler warns that the extension is shadowed.
- Extension properties have no backing field.
val Foo.x = 0is a compile error. Writeval Foo.x: Int get() = ...instead. - An extension function cannot be overridden. It is not part of the class hierarchy.
- The compiler desugars
receiver.ext()to a static method in a generated class (e.g.MyFileKt.ext(receiver)). No vtable entry is created. - You can write extensions on nullable types (
fun String?.orDash(): String) and genericinlineextensions withreifiedtype parameters, like the standardfilterIsInstance<T>(). - Extensions on
AnyorAny?apply to every type and clutter autocomplete everywhere. Prefer extending the most specific type you need. - In Android,
View.isVisible(core-ktx) is an extension property with a custom getter and setter that read and writevisibility. It is not a real field onView.
Code example
This sample shows a small Shape interface, two implementations, and extensions that demonstrate static resolution, the member-vs-extension shadowing rule, and an extension property with a computed getter.
package com.example.ext
// --- interface: members are open by default ---
interface Shape {
fun area(): Double
}
open class Circle(val radius: Double) : Shape {
override fun area(): Double = Math.PI * radius * radius
}
class BigCircle(radius: Double) : Circle(radius) {
// overrides area(); extensions that call area() still get this via virtual dispatch
override fun area(): Double = super.area() * 2.0
}
// --- extension function: static, cannot be overridden ---
fun Shape.describe(): String = "area=" + "%.2f".format(area())
// --- two extensions with the same name: chosen by declared type ---
fun Circle.kind(): String = "circle"
fun BigCircle.kind(): String = "big circle"
// --- extension property: computed getter, no backing field ---
val Shape.isLarge: Boolean
get() = area() > 50.0
// --- member shadows extension ---
class Tag(val label: String) {
fun describe(): String = "member: " + label
}
fun Tag.describe(): String = "extension" // warning: shadowed by member, never called
fun main() {
val c = Circle(3.0)
val b = BigCircle(3.0)
println(c.describe()) // area=28.27
println(b.describe()) // area=56.55 (virtual area() called)
println("b isLarge: " + b.isLarge) // true
val asCircle: Circle = b
println(b.kind()) // big circle
println(asCircle.kind()) // circle: declared type wins
println(Tag("x").describe()) // member: x
}Shapeis an interface so itsarea()is open;Circleis markedopensoBigCirclecan extend it.describe()is an extension onShape; it callsarea(), which is virtual, soBigCircle's override is used.kind()shows static resolution: the same object printsbig circleorcircledepending only on the declared type of the variable.isLargeis an extension property with only a getter. It computes its value on every call and stores nothing.
Run the idea in plain Kotlin
interface Shape {
fun area(): Double
}
open class Circle(val radius: Double) : Shape {
override fun area(): Double = 3.0 * radius * radius
}
class BigCircle(radius: Double) : Circle(radius) {
override fun area(): Double = super.area() * 2.0
}
fun Shape.describe(): String = "area=" + area()
fun Circle.kind(): String = "circle"
fun BigCircle.kind(): String = "big circle"
val Shape.isLarge: Boolean
get() = area() > 50.0
fun main() {
val circle = Circle(3.0)
val big = BigCircle(3.0)
println(circle.describe())
println(big.describe())
println("circle isLarge: " + circle.isLarge)
println("big isLarge: " + big.isLarge)
val asCircle: Circle = big
println("big.kind(): " + big.kind())
println("asCircle.kind(): " + asCircle.kind())
}The playground prints area=27.0, area=54.0, circle isLarge: false, big isLarge: true, then big.kind(): big circle and asCircle.kind(): circle. The last two lines are the same object: only the declared type changed.
In production
- A team wrote two extensions:
fun Throwable.toUserMessage()returning "Something went wrong", andfun HttpException.toUserMessage()returning "Please sign in again" for a 401. - The ViewModel called it as
result.onFailure { showError(it.toUserMessage()) }. InsideonFailure,itis declared asThrowable. - Because extensions are resolved by declared type, the
Throwableversion was always chosen. Users with an expired session saw "Something went wrong" and never got the sign-in prompt. - Unit tests called
HttpException(...).toUserMessage()directly on a variable typedHttpException, so they passed.
- Reproduce with a test that passes the exception as a
Throwable, the way the ViewModel does. It fails before the fix. - Replace the two extensions with one
fun Throwable.toUserMessage()whose body useswhen (this) { is HttpException -> ...; else -> ... }, so the check happens on the runtime type. - Review rule: do not overload an extension for a subtype when callers hold the base type. Branch on the runtime type, or use a member function.
- To debounce clicks, a developer wrote
var Fragment.lastClickTime: Long = 0L. The compiler rejected it: extension properties cannot be initialized because they have no backing field. - To make it compile, they backed the property with a top-level
private var lastClick = 0Land wrote a getter and setter that read and wrote it. - That variable is a single static field, shared by every fragment. A tap on one screen shortly after a tap on another screen was ignored as a "double click".
- Reproduce with a test that clicks on two different fragments within the debounce window and asserts both clicks are handled.
- Move the state into the instance that owns it: a
lastClickTimemember property in the fragment, or a small debouncer object held by each screen. - Team rule: extension properties compute values from the receiver's public state. They never store per-instance state.
Common mistakes
- Assuming an extension is polymorphic. Extensions are resolved at the call site on the declared type. If you store a subclass instance in a base-type variable, the extension on the base type is called, not a subclass-specific one. Use an open member function, or branch on the runtime type inside one extension.
- Trying to access private state from an extension. Reaching into
privatemembers is a compile error. If you need that state, add a member function or expose a property. - Naming an extension the same as an existing member. The member wins and your extension never runs for that call. The compiler warns about it, so do not ignore the "extension is shadowed by a member" warning.
- Giving an extension property an initializer.
val Foo.cache = mutableMapOf<String, Any>()does not compile, because there is nowhere to store it. Backing it with a top-level variable makes it shared by every instance. - Extending Any or Any? for a narrow use case. The extension becomes available on every type, increasing the chance of accidental calls and making refactoring harder. Extend the most specific type you need.
- Using an extension for logic that should be a member. If the logic depends on internal state, needs to be overridden, or must be part of the public contract, it belongs as a member. Extensions suit helpers that only need the public API.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How does the compiler resolve an extension function call?”
“Can an extension function access private members of the class it extends?”
“What happens when a member and an extension have the same signature?”
“Can an extension property have a backing field?”
Quiz
What does the compiler generate for a top-level extension function fun String.shout()?
You declare val s: Base = Sub(). Both fun Base.ext() and fun Sub.ext() exist. Which one does s.ext() call?
Why does val String.firstChar: Char = 'a' fail to compile?
A class has a member fun log(). You also write fun MyClass.log(). Which is called when you write myClass.log()?
0 of 4 answered
Mini task
Exercise: Build a small extension toolkit (15 min)
- Create a new Kotlin file
ExtDemo.ktin a pure-Kotlin project (no Android dependencies). - Define an interface
Animalwith one abstract memberfun sound(): String. - Implement two classes:
Dog(returns "Woof") andCat(returns "Meow"). - Write an extension function
fun Animal.greet(): Stringthat returns "Hello, I say " + sound(). - Write an extension property
val Animal.isLoud: Booleanwith a getter that returnssound().length > 4. - In
main(), store aCatin a variable of typeAnimaland callgreet()andisLoud. Print the results. - Add a class
LoudDogthat overridessound()to return "WOOF WOOF". Store it in anAnimalvariable and callgreet()again. Observe that the innersound()call is virtual (you get "WOOF WOOF") even though the extension is chosen statically. - Add
fun Dog.greet(): String = "Dog extension". Callgreet()on aDogstored in aval d: Dogand in aval a: Animal, and explain the two outputs. - Add a member
fun greet(): String = "member"with a default body toAnimal. Confirm the compiler warns that the extension is shadowed, and thatgreet()now prints the member's result.
Done when: the program compiles, prints greet() output for Cat, Dog and LoudDog, step 8 shows two different results for the same Dog object, and step 9 shows the shadowing warning and the member's result.