Lesson 17 of 17
Scope Functions & Extensions
Scope Functions & Extension Functions
Kotlin provides five scope functions that execute a block of code on an object: let, also, apply, run, and with. They differ in how they refer to the object and what they return.
let
let passes the object as it and returns the lambda result. Often used with safe calls:
val name: String? = "Alice"
val len = name?.let { it.length }
println(len) // 5
also
also passes the object as it and returns the object itself. Great for side effects like logging:
val numbers = mutableListOf(1, 2, 3)
numbers.also { println("Before: $it") }
.add(4)
println(numbers) // [1, 2, 3, 4]
apply
apply gives access to the object as it and returns the object itself. Useful for configuring objects:
val result = mutableListOf(1, 2).apply { it.add(3) }
println(result) // [1, 2, 3]
run
run gives access to the object as it and returns the lambda result:
val greeting = "Hello".run { "$it, World!" }
println(greeting) // Hello, World!
with
with is not an extension — you pass the object as an argument. It returns the lambda result:
val numbers = listOf(1, 2, 3)
val summary = with(numbers) { "Count: ${it.size}" }
println(summary) // Count: 3
Extension Functions
Extension functions let you add new methods to existing types without modifying them:
fun String.exclaim(): String = this + "!"
fun String.repeat3(): String = this + this + this
println("Hello".exclaim()) // Hello!
println("ha".repeat3()) // hahaha
Your Turn
- Write an extension function
String.shout()that returns the string uppercased with"!"appended. - In
main, useletto transform a string,alsofor a side effect, andwithto build a summary.
JS Transpiler loading...
Loading...
Click "Run" to execute your code.