Intermediate 7 min readKotlin 2.0

Kotlin Extension Functions — Add Methods Without Inheriting

Extension functions let you add new functions to existing classes without inheriting from them or modifying their source code.

What You Will Learn

  • Declare extension functions
  • Use "this" in extension functions
  • Extend built-in types like String and Int
  • Understand extension function limitations
  • Nullable receiver extensions

Declaring Extension Functions

Place the receiver type before the function name with a dot.

Basic Extension Function

kotlin
fun String.shout(): String = uppercase() + "!!!"
fun Int.isEven(): Boolean = this % 2 == 0
fun Int.square() = this * this

fun main() {
    println("kotlin".shout())
    println(4.isEven())
    println(7.isEven())
    println(5.square())
}
Output
KOTLIN!!! true false 25

String.shout() extends String. Inside the function, this refers to the receiver (the String). 4.isEven() is called on 4 as if it were a built-in method.

Beginner Tip: this inside an extension function is the object the function is called on — the receiver object.

Extension Functions on Custom Classes

Extend your own classes to add utility functions elsewhere.

Extending a Custom Class

kotlin
data class User(val name: String, val age: Int)

fun User.isAdult() = age >= 18
fun User.greeting() = "Hello, I am $name"

fun main() {
    val user = User("Juned", 25)
    println(user.isAdult())
    println(user.greeting())
}
Output
true Hello, I am Juned

isAdult and greeting are defined outside User but called as if they were methods of User. This keeps the User class clean.

Nullable Receiver Extensions

Extend nullable types using Type? as the receiver.

Nullable Extension

kotlin
fun String?.orEmpty2(): String = this ?: ""

fun main() {
    val a: String? = null
    val b: String? = "Kotlin"
    println(a.orEmpty2())
    println(b.orEmpty2())
}
Output
Kotlin

The receiver type is String? so you can call this function on nullable strings without a safe call. Inside, this is used with ?: to provide an empty string fallback.

The standard library already provides String?.orEmpty(). This example demonstrates the pattern.

Practice Exercise

Exercisepredict output

What prints? fun Int.doubled() = this * 2 fun main() { println(6.doubled()) }

Quick Quiz

Quick Quiz

Can an extension function access private members of the extended class?

Frequently Asked Questions

Related Tutorials

Last updated: 2026-05-01Kotlin 2.0

Written by KotlinGuide Editorial Team · Reviewed by KotlinGuide Technical Review