Extension Functions in Kotlin
From the Kotlin cheat sheet · Extensions · verified Jul 2026
Extension Functions
Adding functions to existing types
kotlin
// Extension function
fun String.removeSpaces(): String {
return this.replace(" ", "")
}
val text = "Hello World"
println(text.removeSpaces()) // HelloWorld
// Extension properties
val String.lastChar: Char
get() = this[length - 1]
println("Kotlin".lastChar) // n
// Extensions on nullable types
fun String?.isNullOrEmpty(): Boolean {
return this == null || this.isEmpty()
}
val nullString: String? = null
println(nullString.isNullOrEmpty()) // true
// Generic extensions
fun <T> List<T>.secondOrNull(): T? {
return if (size >= 2) this[1] else null
}💡 Extensions add functions without modifying original class
⚡ Extensions are resolved statically, not polymorphically
📌 Member functions always win over extensions
🟢 Can extend nullable types with null-safe operations