Code
kotlin
// 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") }