Official page is here
inline fun <T> T.apply(block: T.() -> Unit): T
The context object is available as a receiver (this). The return value is the object itself.
Example:
class User(var name: String, var age: Int)
val user = User("John", 25) //John, 25
val anotherUser = user.apply {
age = 32
} //John, 32
inline fun <T> T.also(block: (T) -> Unit): T
The context object is available as an argument (it). The return value is the object itself.
Example:
data class User(val name: String, val age: Int)
val user = User("John", 25)
user.also {
println("I'm ${it.name} and I'm ${it.age} years old")
}
inline fun <T, R> T.let(block: (T) -> R): R
The context object is available as an argument (it). The return value is lambda result
Example:
data class User(val name: String, val age: Int)
val user = User("John", 25)
val ageAfter5Years = user.let { it.age + 5 } // 30
The context object is available as a receiver (this). The return value is lambda result.
Example:
data class User(val name: String, val age: Int)
val user = User("John", 25)
val nameUppercase = user.run { name.toUpperCase() } //JOHN
It can also run without context object
val area = run {
val r = 20.0
const val PI = 3.1415
PI*r*r
}
Example:
class User(val name: String, val age: Int) {
fun indroduce() {
println("I'm ${it.name} and I'm ${it.age} years old")
}
}
val user = User("John", 25)
with(user) {
println("Introducing ${name}")
this.introduce()
}
Used with Closeables. Calls close()
at the end of the block
Example:
Files.newOutputStream(path).use {
it.write("Hello")
} //close() is called here
To define as this
:
class Dog(var name: String) {
fun bark() { println("Woof woof") }
}
fun Dog.doStuff(block: Dog.() -> Unit) {
println("Doing dog stuff...")
block(this)
}
val dog = Dog("Bob")
dog.doStuff {
println("I'm $name")
bark()
}
To define as it
:
class Cat(var name: String) {
fun meaw() { println("Meaow!") }
}
fun Cat.doStuff(block: (Cat) -> Unit) {
println("Doing cat stuff...")
block(this)
}
val cat = Dog("Kitty")
cat.doStuff {
println("I'm ${it.name}")
it.meaow()
}