Extension functions

Kotlin language Mid-level Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Predict the output

What does this print?

open class Shape
class Circle : Shape()

fun Shape.name() = "shape"
fun Circle.name() = "circle"

fun main() {
    val s: Shape = Circle()
    println(s.name())
}
Options
Hint 1 of 1

Is the call decided at compile time or at runtime?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A shape

Correct. Extensions are resolved by the declared type, which is Shape.

Why not the others?
  • B circle. That would be a member override; extensions aren't virtual.
  • C It doesn't compile: ambiguous call. Each extension has a different receiver type, so there's no ambiguity.
  • D Circle@1a2b3c. name() returns a String literal.

30-second answer

An extension function adds a function to a type without changing it: fun String.initials(): String. It compiles to a static function that takes the receiver as its first parameter. So extensions are resolved statically by the declared type, not the runtime type, and a member function with the same signature always wins.

Practise saying it · 30 s. No recording, just a timer

Explain how extension functions work.

Say your answer out loud, then check which of these points you covered:

  • Add functions without changing the class
  • Compiled to static functions
  • Resolved by declared type
  • Members win

Deep dive

Extensions can't access private members of the class.

Nullable receivers are allowed: fun String?.orDash() = this ?: "-".

Extension properties can't have backing fields; they're computed.

Keep extensions discoverable: put them near the type or in a clearly named file.

Common mistakes

  • Expecting an extension to be overridden like a virtual method.
  • Defining an extension that shadows a member and wondering why it's never called.
  • Hiding important behaviour in scattered extension files.

Senior take & follow-ups

Say 'statically dispatched', then show the base-type example.

Follow-up questions

Think of your answer first, then open the hint.

  1. Can an extension access private fields?

    Show hint

    No; it's a static function outside the class.

  2. What if a member has the same signature?

    Show hint

    The member wins.

Suggest a fix if something here is wrong or out of date.