Skip to main content
Browse topics

Extension Functions in Kotlin

2 min read Updated June 30, 2026
Share

Introduction

Extension Functions is a fundamental concept every Kotlin developer should understand. Extension functions add methods to existing classes without inheritance — a core Kotlin idiom used throughout the standard library.

Extension functions add new behaviour to existing types without modifying their source. In this tutorial you will learn the syntax, walk through a complete example program, study the sample output, and review best practices so you can apply the concept confidently in your own projects.

Definition

  • Extension functions add new behaviour to existing types without modifying their source.
  • They are resolved statically based on the declared receiver type.
  • The Kotlin standard library uses extensions extensively for strings and collections.

Syntax

kotlin
fun String.lastChar(): Char = this[this.length - 1]

Extension Functions in Kotlin Example Program in Kotlin

kotlin
fun String.lastChar(): Char = this[this.length - 1]
fun Int.isPositive() = this > 0

fun main() {
    val text = "Kotlin"
    println("Last char of $text is ${text.lastChar()}")
    println("Is 10 positive? ${10.isPositive()}")
}

Sample Output

plaintext
Last char of Kotlin is n
Is 10 positive? true

When to use

Use extensions to add domain-specific helpers to String, List, or third-party types you cannot modify.

How it works

  1. The program starts with a main function — the entry point that runs when you execute the file.

  2. Extension functions add new behaviour to existing types without modifying their source.

  3. Run the program in IntelliJ IDEA, Android Studio, or with the Kotlin command-line compiler (kotlinc / kotlin). Compare your console output with the sample output shown below.

Best Practices

Common Mistakes

Key Points

  • Extension functions add new behaviour to existing types without modifying their source.
  • They are resolved statically based on the declared receiver type.
  • The Kotlin standard library uses extensions extensively for strings and collections.
  • Test the example locally and verify the output matches the sample.
  • Experiment by changing input values to see how behaviour changes.

Notes

  • Semicolons at the end of statements are optional in Kotlin.

Frequently Asked Questions

What is Extension Functions in Kotlin?
Extension functions add new behaviour to existing types without modifying their source.
When should I use Extension Functions?
Use extensions to add domain-specific helpers to String, List, or third-party types you cannot modify.
How is Extension Functions different from Java?
The Kotlin standard library uses extensions extensively for strings and collections.
How do I practice this topic?
Copy the example program into IntelliJ IDEA or Android Studio, run it, then modify values or add print statements to confirm your understanding.

Related tutorials

Search tutorials