Kotlin

Extension Functions

admin by @admin ADMIN
12m ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Add methods to ANY type — including stdlib types like String, List, or Int — without subclassing. Compiled as a static dispatched function, so no runtime overhead.
Kotlin
Raw
// Extension function on String
fun String.isPalindrome(): Boolean =
    this == this.reversed()

// Extension function on List<Int>
fun List<Int>.median(): Double {
    val s = sorted()
    val n = s.size
    return if (n % 2 == 0) (s[n/2 - 1] + s[n/2]) / 2.0 else s[n/2].toDouble()
}

// Nullable receiver — handle the null case inside the extension
fun String?.isNullOrBlankSafely(): Boolean = this == null || this.isBlank()

fun main() {
    println("racecar".isPalindrome())                   // true
    println("hello".isPalindrome())                     // false

    println(listOf(1, 3, 5, 7, 9).median())             // 5.0
    println(listOf(1, 2, 3, 4).median())                // 2.5

    val s: String? = null
    println(s.isNullOrBlankSafely())                    // true
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.