Skip to content
tezvyn:

Kotlin Extension Functions: Add Methods Without Inheritance

Source: kotlinlang.orgHardHow cards are made

Kotlin Extension Functions: Add Methods Without Inheritance

Kotlin extension functions let you add new functionality to existing classes without inheritance, as if you were adding a new method. They're perfect for creating helpers for third-party library classes or framework types like String.

Why it exists

To add functionality to classes we cannot or should not modify. Sometimes you need a helper method on a class from a third-party library or a core framework class like String. Inheritance isn't always feasible or desirable, and extension functions provide a cleaner, more direct alternative without using complex design patterns.

The mental model

Think of extension functions as syntactic sugar for static utility methods. Instead of writing a standalone helper like Utils.truncate(myString, 10), you can define an extension and write the more object-oriented myString.truncate(10). The function doesn't actually get added to the original class; the compiler just rewrites your call to the static helper behind the scenes.

How it works

You declare a function by prefixing its name with the "receiver type"—the class you want to extend—followed by a dot. For example, fun String.initials(): String. Inside the function body, the this keyword refers to the instance of the receiver type (the specific String the function was called on). These functions are then callable on any instance of the receiver type as if they were native methods.

When to use it

Use extensions to add utility functions to classes you don't control, like those from external libraries. They are also great for adding domain-specific helpers to common types (like a toPrice() extension on Double) or for adding functionality to all implementers of an interface in one place. The Kotlin standard library itself uses them extensively for collections, with functions like .map(), .filter(), and .groupBy().

When not to use it

Avoid using extensions to alter the core behavior of a class or to add functionality that truly belongs inside the class itself if you have the ability to modify it. Overusing them can pollute the global namespace and make code harder to navigate, as it's not immediately obvious where the extended method is defined. Always check the standard library first to avoid reinventing existing functionality.

One canonical example

A common use case is adding a custom truncation function to the String class. fun String.truncate(maxLength: Int): String { return if (this.length <= maxLength) this else take(maxLength - 3) + "..." } Now, any string in your project can call this function: val longText = "This is a very long piece of text." println(longText.truncate(20)) // Prints "This is a very lo..."

Interview question

Which statement accurately describes how Kotlin extension functions fundamentally add functionality to a class?

  • a.The compiler transforms calls to them into static utility method invocations, passing the receiver object as an argument.Correct
  • b.They create an anonymous inner class that wraps the original class and exposes the new method.
  • c.They leverage runtime reflection to dynamically attach new methods to instances of the receiver class.
  • d.They modify the original class's definition by injecting new methods into its bytecode.
Why?

Kotlin extension functions are syntactic sugar; the compiler rewrites calls to them as static utility method calls, passing the receiver instance as an argument. They do not modify the original class's bytecode, create new classes, or use reflection to add methods dynamically.

Just read this? Test yourself on what you have been reading.

Read the original → kotlinlang.org

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on kotlin — each one lists the topics its interview covers.

See open roles