Skip to content

Step 1 of 6 · Reading · ~1 min

Learn

Idiomatic Kotlin

Extension functions add methods to existing types without modifying them. Defined outside the class:

fun String.shout(): String = this.toUpperCase() + "!"

"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 = sumBy { it * it }

// In another file:
import com.example.utils.sumOfSquares
listOf(1, 2, 3).sumOfSquares()   // 14

An extension never wins against a member: if the receiver's class already declares a function with the same name and signature, the member is called and your extension is ignored (with a warning). Extensions also see only the public API of the receiver — no reaching into its private fields.

This course grades on Kotlin 1.3, where the uppercasing extension is toUpperCase(); the uppercase() spelling arrived in 1.5 and will not compile here.

Kotlin's standard library is built largely on extensions — List.map, String.toUpperCase(), etc. are all extensions on existing types.

Up nextScope Functions: let, run, with, apply, alsoIdiomatic Kotlin

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…