Kotlin

Extension Properties

admin by @admin ADMIN
4h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Like extension functions, but as a property. Must have a custom getter (and optionally a setter) since extensions can't have backing fields. Reads like a real property at the call site.
Kotlin
Raw
// String extension properties
val String.wordCount: Int
    get() = trim().split("\\s+".toRegex()).filter { it.isNotEmpty() }.size

val <T> List<T>.lastIndex: Int
    get() = size - 1

// Pair where both halves are the same: doubled
val <T> T.asPair: Pair<T, T>
    get() = this to this

fun main() {
    println("hello world foo bar".wordCount)        // 4

    val xs = listOf("a", "b", "c", "d")
    println(xs.lastIndex)                           // 3 (built-in too, but instructive)

    println(42.asPair)                              // (42, 42)
    println("hi".asPair)                            // (hi, hi)
}
Tags

Save your own code snippets

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