Extension Functions and Properties

Extension Functions and Properties in Kotlin: --- A great reference library holds tens of thousands of books it did not write and may not alter.


The Analogy: The Reference Library and the Supplementary Index Cards

A great reference library holds tens of thousands of books it did not write and may not alter. The bindings are the publishers', the text is fixed, and a librarian who wanted to add a chapter or correct a figure has no right to touch the page. What the librarian can do is file a supplementary index card in a drawer beside the shelves: a card that says "plain-language summary of this volume," or "known errata," or "see also the companion atlas." The card adds a new service on top of a book the library does not own. That card is an extension: behaviour attached to a type you cannot modify, living outside it, reaching only what the book already shows the world on its printed pages.

Here is the subtlety that catches everyone. When a reader hands in a request slip -- "the summary of the work classified as a Timetable" -- the librarian pulls the summary card filed under Timetable. The card is selected by the classification written on the request slip, not by walking to the shelf and examining the actual book. If the slip says Timetable, the Timetable card is fetched even if the volume physically standing in that slot was rebound and is really a Gazetteer. The label on the request decides which card is pulled; the true nature of the book on the shelf never enters into it. This is static resolution: an extension is chosen by the declared type of the expression, settled when the request is written, not by the runtime object.

There is one thing the supplementary card can never win against. If the publisher printed a summary on the book's own dust jacket, the librarian is instructed to read the jacket and never consult the drawer. The book's own printed matter always takes precedence over any card filed beside it. So a member the type declares itself will always be preferred to an extension of the same name -- the jacket beats the card every time, and the card is consulted only when the jacket is silent.

The failure mode follows from both rules at once. A card may only summarise what the book prints in public; it cannot cite the author's private notes locked in the archive, so a card that promises to reveal them is filing a promise it cannot keep. And the day a publisher issues a new edition with a summary freshly printed on the jacket, every reader who used to receive the librarian's carefully written card now silently receives the publisher's instead -- the card is not removed, it is simply never reached again, and no one is told the service changed. A drawer of supplementary cards is a convenience bolted to the side of a collection, never a part of the books themselves.


Syntax or Core Structure

fun String.shout(): String = uppercase() + "!"

val String.wordCount: Int
    get() = trim().split(" ").filter { it.isNotEmpty() }.size

fun String.repeatWith(sep: String, n: Int): String {
    val parts = ArrayList<String>()
    for (i in 0 until n) parts.add(this)
    return parts.joinToString(sep)
}

fun main() {
    println("all aboard".shout())
    println("words: " + "  the  night mail ".wordCount)
    println("echo: " + "toot".repeatWith("-", 3))
}

An extension function names the receiver type before the dot: fun String.shout() reads as "a function shout available on any String." Inside the body, this is the receiver, and its public members can be called without qualification -- uppercase() means this.uppercase(). An extension property, val String.wordCount, is declared the same way but must supply a getter and can hold no state of its own. The third function shows this used explicitly: each iteration adds the receiver string to the list.

Output:

ALL ABOARD!
words: 3
echo: toot-toot-toot

The word count is 3 because trim removes the outer spaces, split(" ") on the doubled inner space yields an empty string between "the" and "night", and filter drops it. The echo joins three copies of "toot" with a hyphen.


Technical Depth: Static Resolution and What Extensions Cannot Do

An extension is chosen by the declared type, not the runtime object

This is the single most important fact about extensions, and the one that produces "impossible" output until you internalise it. An extension call compiles to a plain static function call with the receiver passed as the first argument. There is no virtual table, no dynamic dispatch. The compiler picks which extension to call using the static type of the receiver expression at the call site, and that decision is frozen at compile time.

open class Book
class Manual : Book()

fun Book.shelfTag(): String = "general"
fun Manual.shelfTag(): String = "technical"

fun describe(b: Book): String = b.shelfTag()

fun main() {
    val m = Manual()
    println(m.shelfTag())
    println(describe(m))
    val b: Book = Manual()
    println(b.shelfTag())
}

Output:

technical
general
general

Every one of these calls is made on an object that is really a Manual. Yet only the first prints technical. In describe, the parameter b is declared Book, so b.shelfTag() binds to Book.shelfTag at compile time and returns general, even though the argument is a Manual. The third call assigns a Manual to a variable declared Book and gets the same result. Had shelfTag been an ordinary open member, all three would print technical; because it is an extension, the declared type wins.

The declared member always beats the extension

If a type declares a member function and you write an extension with the same name and parameters, calls resolve to the member. The extension is not an error and not a warning -- it is simply never reached for that signature.

class Ticket {
    fun code(): String = "member"
}

fun Ticket.code(): String = "extension"

fun main() {
    println(Ticket().code())
}

Output:

member

The consequence for maintenance is sharp: if you write an extension code() on a class you do not own, and a later version of that class adds its own code() member, your call sites silently switch to the member. Nothing breaks the build; the behaviour just changes underneath you.

The table below fixes the five properties that trip people up. Read the middle column as the rule and the right column as the reason.

PropertyThe ruleWhy
dispatchresolved by declared typecompiled as a static call, no vtable
vs membermember of the same signature winsthe type's own API takes precedence
extension propertyno backing field allowedit is a getter, storing nothing
private accesssees only the public and internal APIit lives outside the class body
nullable receivermay be called on a null valuethe receiver is just an argument

Extension properties store nothing, and nullable receivers accept null

An extension property is a getter dressed as a field. It cannot declare a backing field, so it can only compute from what the receiver already exposes. And because the receiver is really just the first argument, an extension may be declared on a nullable type and called safely on null.

val String.initials: String
    get() = trim().split(" ").filter { it.isNotEmpty() }
        .joinToString("") { it.first().uppercase() }

fun List<Int>?.sumOrZero(): Int = this?.sum() ?: 0

fun main() {
    println("north eastern railway".initials)
    val present: List<Int>? = listOf(3, 4, 5)
    val absent: List<Int>? = null
    println("present: " + present.sumOrZero())
    println("absent: " + absent.sumOrZero())
}

Output:

NER
present: 12
absent: 0

initials computes from the words of the receiver and stores nothing between calls. sumOrZero is declared on List<Int>?, so it can be called on absent without a null check at the call site; inside, this is null and the elvis operator supplies 0. A member function could never be called on a null receiver -- only an extension can, precisely because the receiver is passed as an argument rather than dispatched upon.


Real World Example: A Pre-Decimal Ledger

Before 1971 British money ran on 12 pence to the shilling and 20 shillings to the pound, so 240 pence made a pound. The program below adds a small vocabulary to the plain Int for reading a total in pence as pounds, shillings and pence: three extension properties and one extension function. It prints a ledger, decomposes each amount, and totals the column of pence.

const val PER_POUND = 240
const val PER_SHILLING = 12
const val LEDGER = "petty:250,wages:1000,carriage:60,sundries:239,rent:481"
const val W_NAME = 10
const val W_PENCE = 7
const val W_L = 4
const val W_S = 4
const val W_D = 4

val Int.pounds: Int get() = this / PER_POUND
val Int.shillings: Int get() = (this % PER_POUND) / PER_SHILLING
val Int.pence: Int get() = this % PER_SHILLING

fun Int.asLSD(): String = pounds.toString() + "/" + shillings.toString() + "/" + pence.toString()

fun row(name: String, pence: String, l: String, s: String, d: String): String =
    name.padStart(W_NAME) + pence.padStart(W_PENCE) + l.padStart(W_L) +
        s.padStart(W_S) + d.padStart(W_D)

fun main() {
    val entries = LEDGER.split(",").map { it.split(":") }
    val ruleWidth = W_NAME + W_PENCE + W_L + W_S + W_D
    println(row("NAME", "PENCE", "L", "S", "D"))
    println("-".repeat(ruleWidth))

    var totalPence = 0
    var sumL = 0
    var sumS = 0
    var sumD = 0
    for (e in entries) {
        val name = e[0]
        val pence = e[1].toInt()
        totalPence += pence
        sumL += pence.pounds; sumS += pence.shillings; sumD += pence.pence
        println(row(name, pence.toString(),
            pence.pounds.toString(), pence.shillings.toString(), pence.pence.toString()))
    }
    println("-".repeat(ruleWidth))
    println(row("TOTALS", totalPence.toString(),
        totalPence.pounds.toString(), totalPence.shillings.toString(), totalPence.pence.toString()))

    println("amounts: " + entries.size)
    val reassembled = totalPence.pounds * PER_POUND +
        totalPence.shillings * PER_SHILLING + totalPence.pence
    println("reassemble " + totalPence.asLSD() + " -> " + reassembled +
        " agree: " + (reassembled == totalPence))
    println("column sums L=" + sumL + " S=" + sumS + " D=" + sumD +
        " as pence " + (sumL * PER_POUND + sumS * PER_SHILLING + sumD))
    val strayShillings = totalPence.shillings
    println("shillings " + strayShillings + " read as pence: " + strayShillings.asLSD())
}

Output:

      NAME  PENCE   L   S   D
-----------------------------
     petty    250   1   0  10
     wages   1000   4   3   4
  carriage     60   0   5   0
  sundries    239   0  19  11
      rent    481   2   0   1
-----------------------------
    TOTALS   2030   8   9   2
amounts: 5
reassemble 8/9/2 -> 2030 agree: true
column sums L=7 S=27 D=26 as pence 2030
shillings 9 read as pence: 0/0/9

Trace the sundries row. 239 pence is fewer than a pound, so pounds is 0. The remainder 239 divides by 12 to give 19 shillings with 11 left over, so shillings is 19 and pence is 11, printed as 0 19 11. Every row satisfies the same identity: the pence figure equals pounds * 240 + shillings * 12 + pence. The TOTALS line is not a sum of the L, S and D columns above it -- it is computed by summing the pence column to 2030 and then decomposing that with the same three extension properties, which is why it reads 8 9 2.

The reassemble line proves the decomposition loses nothing: it takes the total's own pounds, shillings and pence, multiplies them back up, and confirms the result equals the original 2030. This is a genuine check of the extension-property arithmetic, not a tautology -- a wrong divisor would make it disagree. The column sums line shows why the totals were computed from pence and not from the columns: adding each column independently gives 7 pounds, 27 shillings and 26 pence, an un-normalised figure that no clerk would write, even though it happens to reassemble to the same 2030 pence. Shillings and pence carry, and only converting from a single pence total respects the carry.

The last line exposes the genuine design flaw, and it is one the extension vocabulary invites. The total's shillings component is the bare Int 9. Nothing about that 9 records that it means shillings rather than pence, so when it is handed to asLSD, the function reinterprets it as 9 pence and returns 0/0/9 without complaint. Every value here is a naked Int, and any extension defined for pence will silently accept any other integer, whatever it was meant to represent. The extensions give the comfortable illusion of a money vocabulary while providing none of its safety; a real Pence value class would make 9.shillings.asLSD() a type error rather than a plausible wrong answer. A narrower limit is the familiar one: padStart never truncates, so the first ledger name longer than ten characters would misalign the board.


Common Mistakes

  1. Expecting an extension to dispatch on the runtime type. An extension is resolved by the declared type of the receiver expression, decided at compile time. An extension on a base type, called through a base-typed variable, runs the base version even when the object is really a subtype. Extensions are not polymorphic.
  1. Believing an extension can override a member. When a member function and an extension share a signature, the member always wins and the extension is silently ignored for that call. You cannot use an extension to change a method the type already declares.
  1. Adding a member that shadows an existing extension without noticing. If a class you extended later gains a member of the same signature, every call site quietly switches from your extension to the new member. The build stays green while the behaviour changes, which makes this a genuinely dangerous upgrade hazard.
  1. Trying to give an extension property a backing field. An extension property is a getter and can store nothing. Writing val String.tag: String = "" does not compile, because there is no field to hold the value; you must compute it in a getter from what the receiver already exposes.
  1. Assuming an extension can reach private members. An extension declared outside the class sees only its public and internal API, exactly as any other outside caller would. It cannot touch private fields, so it cannot do things a real member could.
  1. Forgetting extensions must be imported into scope. An extension is not "added to the class" everywhere; it is a top-level function visible only where its declaration is in scope or imported. Two files can define different extensions of the same name, and which one applies depends on the imports in force.
  1. Neglecting the null case in a nullable-receiver extension. An extension on T? can be called on null, and inside the body this may be null. Calling a member on this without a null check throws exactly the exception the nullable receiver was meant to let you handle.
  1. Shadowing a standard-library extension by import. Defining your own sumBy or firstOrNull and importing it alongside the stdlib version leads to resolution that depends on import order and visibility, producing confusing "wrong overload" behaviour that is hard to spot.
  1. Using extensions to fake a domain type on a primitive. A cluster of extensions on Int reads like a money or duration vocabulary, but every value remains a bare Int that any other extension will happily reinterpret. When you need a real invariant, define a type; do not lean on extensions to enforce one they cannot.

Best Practices

  • Reach for extensions to add focused, stateless helpers to types you do not own -- formatting, adapting, querying -- rather than to smuggle in behaviour that wants to be a real member.
  • Keep extension properties cheap and free of side effects, because at the call site they look exactly like fields and readers will assume they are.
  • Do not try to make extensions polymorphic; when you need behaviour that varies by runtime type, put it in a member or behind an interface where dispatch is virtual.
  • Prefer a genuine type -- a value class or data class -- over a swarm of extensions on a primitive whenever you need an invariant the compiler should enforce.
  • Place related extensions in a clearly named file or package and import them deliberately, so their scope is obvious and collisions are avoided.
  • Avoid defining an extension whose signature could clash with an existing or plausibly-future member of the target type, since the member will always shadow it.
  • Handle null explicitly in every nullable-receiver extension, and use such extensions sparingly, only where calling on null genuinely reads better than a check.
  • Design extensions against the public API of the type and document that they cannot see its private state, so no one expects member-only powers from them.

Practice Exercises

  1. Write an extension function String.wordCount(): Int and an extension property val String.firstWord: String that returns the first whitespace-separated word. Test both on a string with leading, trailing and doubled spaces, and verify the results against a hand trace.
  1. Define open class A, class B : A(), extensions fun A.name() and fun B.name(), and a function fun show(a: A): String = a.name(). Predict what show(B()) prints and what B().name() prints, then run both and explain the difference in terms of static resolution.
  1. On a class you write, declare a member function tag() and an extension fun YourClass.tag() with the same signature. Call it and record which runs. Then delete the member and call again, and explain why the output changed even though the call site did not.
  1. Write a nullable-receiver extension fun List<Int>?.sumOrZero(): Int that returns 0 when the receiver is null and the sum otherwise. Verify it on a null List<Int>? and on a non-null list, and explain why a member function could not offer the same call on null.