Extension & Scope Functions
Extension functions
Add new functions to existing classes, even ones you don't own:
fun String.isEmail() = contains("@") && contains(".")
"ana@mail.com".isEmail() // true
val Int.minutes get() = this * 60 // extension property
They don't really change the class; it's neat syntax for a function taking the receiver. They're used everywhere in Android KTX: view.isVisible = true, context.toast("Hi").
Scope functions
They run a block of code on an object, and differ in how you refer to the object and what they return:
| Function | Object inside as | Returns | Typical use |
|---|---|---|---|
let | it | the lambda result | null checks: x?.let { … }, transforming |
run | this | the lambda result | compute a result with the object |
with(obj) | this | the lambda result | several calls on one object |
apply | this | the object | configuring a new object |
also | it | the object | side effects such as logging and validation |
val user = User().apply {
name = "Ana"
age = 20
}.also { println("Created $it") }
val length = name?.let { it.trim().length } ?: 0
Choosing quickly
- Building or configuring something → apply.
- Doing something extra without changing the result → also.
- Working with a nullable value → ?.let.
- Calculating a value from an object → run / with.
⚠️ Don't nest them deeply; readability comes first.
Example
fun String.isEmail() = contains("@") && substringAfter("@").contains(".")
fun String.initials() = split(" ").filter { it.isNotBlank() }.joinToString("") { it.first().uppercase() }
val Int.minutes get() = this * 60
fun <T> List<T>.second(): T? = getOrNull(1)
class Profile {
var name = ""
var age = 0
var skills = mutableListOf<String>()
override fun toString() = "Profile($name, $age, $skills)"
}
fun main() {
println("ana@mail.com".isEmail())
println("not-an-email".isEmail())
println("Asha Kumari Rai".initials()) // AKR
println("25 minutes = ${25.minutes} seconds")
println(listOf("a", "b", "c").second())
val profile = Profile().apply { // configure → returns the object
name = "Ana"
age = 20
skills += "Kotlin"
}.also { println("Created: $it") } // side effect → returns the object
val nickname: String? = " annie "
val len = nickname?.let { it.trim().length } ?: 0
println("Nickname length: $len")
val summary = with(profile) { "$name knows ${skills.size} skill(s)" }
println(summary)
val isAdult = profile.run { age >= 18 }
println("Adult? $isAdult")
}