In Kotlin, scope functions are a set of functions that allow you to apply some operations on an object within a certain scope. These functions provide a convenient way to execute a block of code on an object and return either the object itself or a modified version of the object.
Kotlin has five scope functions:
returns the object itself. It is useful when you want to modify an object's properties in a concise way.data class Person(var name: String, var age: Int, var address: String)
fun main() {
val person = Person("John Doe", 30, "123 Main St")
val modifiedPerson = person.apply { this
name = "Jane Doe"
age = 25
}
}
this).fun main() {
val person = Person("John Doe", 30, "123 Main St")
with(person) {
println("The person's name is $name, they are $age years old, and they live at $address.")
}
}
it).fun main() {
val text: String? = "hello"
val result = text?.also {
println("The original string was $it")
}?.toUpperCase()
println(result)
}
it).let is often used to execute a code block containing non-null valuesval str: String? = null
//processNonNullString(str) // compilation error: str can be null
val length = str?.let {
println("let() called on $it")
}
this).