Reading — step 1 of 6
Learn
~1 min readIdiomatic Kotlin
Extension functions add methods to existing types without modifying them. Defined outside the class:
fun String.shout(): String = this.uppercase() + "!"
"hello".shout() // "HELLO!"
Inside the function body, this refers to the receiver. The function is dispatched statically based on the static type — it's not real polymorphism, just syntactic sugar.
Use cases:
- Add domain-specific methods to standard library types
- Make code read more like natural language:
5.minutes,"abc".isPalindrome() - Provide null-safe variants:
String?.orEmpty()
Extension on nullable types:
fun String?.isNullOrShort(): Boolean = this == null || this.length < 3
val s: String? = null
println(s.isNullOrShort()) // true (no NPE)
Scope-limited — extensions are not part of the type. They're resolved by import:
// In file utils.kt:
fun List<Int>.sumOfSquares(): Int = sumOf { it * it }
// In another file:
import com.example.utils.sumOfSquares
listOf(1, 2, 3).sumOfSquares() // 14
Kotlin's standard library is built largely on extensions — List.map, String.toUpperCase(), etc. are all extensions on existing types.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…