Extension functions and properties

Learn Kotlin extension functions and properties in Android to understand static resolution, lack of private access, and how they are desugared. About 22 minutes.

Why it matters

  • Extensions appear everywhere in Android code (View.isVisible from core-ktx, or your own Context.dp helpers). Knowing they are static, not virtual, prevents subtle bugs when a subclass changes behaviour.
  • Interviewers ask whether an extension can access private members, 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:

AspectMember functionExtension function
DispatchVirtual (runtime type)Static (compile-time type)
Access to private membersYesNo
Access to internal membersYesYes, from the same module
Can be overriddenYes (if open)No
Backing field for propertyYesNever
Can be generic / reifiedGeneric yes, reified only if inlineGeneric 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() picks Shape.describe, not a Circle-specific extension.
  • An extension cannot access private or protected members of the class it extends. It can access internal members 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 = 0 is a compile error. Write val 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 generic inline extensions with reified type parameters, like the standard filterIsInstance<T>().
  • Extensions on Any or Any? 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 write visibility. It is not a real field on View.

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
}
  • Shape is an interface so its area() is open; Circle is marked open so BigCircle can extend it.
  • describe() is an extension on Shape; it calls area(), which is virtual, so BigCircle's override is used.
  • kind() shows static resolution: the same object prints big circle or circle depending only on the declared type of the variable.
  • isLarge is 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

Every error showed the generic message
  • A team wrote two extensions: fun Throwable.toUserMessage() returning "Something went wrong", and fun HttpException.toUserMessage() returning "Please sign in again" for a 401.
  • The ViewModel called it as result.onFailure { showError(it.toUserMessage()) }. Inside onFailure, it is declared as Throwable.
  • Because extensions are resolved by declared type, the Throwable version 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 typed HttpException, so they passed.
The fix
  • 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 uses when (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.
One click timestamp shared by every screen
  • 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 = 0L and 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".
The fix
  • 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 lastClickTime member 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 private members 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)

  1. Create a new Kotlin file ExtDemo.kt in a pure-Kotlin project (no Android dependencies).
  2. Define an interface Animal with one abstract member fun sound(): String.
  3. Implement two classes: Dog (returns "Woof") and Cat (returns "Meow").
  4. Write an extension function fun Animal.greet(): String that returns "Hello, I say " + sound().
  5. Write an extension property val Animal.isLoud: Boolean with a getter that returns sound().length > 4.
  6. In main(), store a Cat in a variable of type Animal and call greet() and isLoud. Print the results.
  7. Add a class LoudDog that overrides sound() to return "WOOF WOOF". Store it in an Animal variable and call greet() again. Observe that the inner sound() call is virtual (you get "WOOF WOOF") even though the extension is chosen statically.
  8. Add fun Dog.greet(): String = "Dog extension". Call greet() on a Dog stored in a val d: Dog and in a val a: Animal, and explain the two outputs.
  9. Add a member fun greet(): String = "member" with a default body to Animal. Confirm the compiler warns that the extension is shadowed, and that greet() 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.

Next: Generics and variance basics