Extension Functions
Add methods to existing types with extensions and infix operators.
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
Null Safety
Use nullable types, safe calls, Elvis, and smart casts for null-safe code.
Data Classes
Model immutable data with auto-generated equals, copy, and destructuring.
Coroutines
Use launch, async, await, and structured concurrency with supervisorScope.
Sealed Classes
Model closed hierarchies and UI state with sealed classes and when.
When Expression
Branch on values, ranges, and types with when as statement or expression.
Collections
Filter, map, group, partition, and chunk with functional operators.