Skip to content
Kotlin

Extension Functions

Add methods to existing types with extensions and infix operators.

By EZ4Code Team
extensionfunction

Code

// Extension on String
fun String.slugify(): String =
    lowercase()
        .replace(Regex("[^a-z0-9]+"), "-")
        .trim('-')

println("Hello, World!".slugify())   // hello-world

// Extension property (computed)
val String.isPalindrome: Boolean
    get() = this == reversed()

println("racecar".isPalindrome)
println("hello".isPalindrome)

// Extension on nullable receiver
fun String?.orDash(): String = this ?: "-"

val s: String? = null
println(s.orDash())

// Generic extension
fun <T> List<T>.second(): T? = if (size >= 2) get(1) else null
println(listOf(1, 2, 3).second())

// Infix extension
infix fun Int.timesStr(s: String): String = s.repeat(this)
println(3 timesStr "ab")

// Extension on standard library
fun List<Int>.sumOfSquares() = sumOf { it * it }
println(listOf(1, 2, 3).sumOfSquares())

// Scoped extension via run/let/also
"hello".also { println("before: $it") }
        .let { it.uppercase() }
        .also { println("after: $it") }

Explanation

Extension functions add methods to existing types without modifying their source, resolved statically by the receiver type. Extension properties work the same way for computed-only values. Combined with nullable receivers and infix notation, they enable fluent DSLs and helper libraries that read like native API.

More Kotlin Snippets