Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Exmaples of 5 Kotlin Scoping functions, Run, With, Let, Apply, Also
class ScopingFunctions {
fun main() {
val firstPerson = Person("Prokash", 28, "Programmer")
val secondPerson = Person("Elizabeth", 34, "Singer")
//Calls the specified function block with this value as its receiver and returns its result.
run {
if (firstPerson.age > secondPerson.age) firstPerson else secondPerson
}.printPerson()
//Extension Function
//Calls the specified function block with this value as its receiver and returns its result.
firstPerson.run {
age += 1
"Age is now $age"
}.println()
//Calls the specified function block with the given receiver as its receiver and returns its result.
with(firstPerson) {
age += 1
"Age is now $age"
}.println()
//Calls the specified function block with this value as its argument and returns its result.
firstPerson.let {
it.age += 1
"Age is now ${it.age}"
}.println()
//Calls the specified function block with this value as its receiver and returns this value.
//Returns the original object after modification
firstPerson.apply {
age += 1
profession = "Engineer"
}.printPerson()
//Calls the specified function block with this value as its argument and returns this value.
//Returns the original object after modification
firstPerson.also {
it.age += 1
it.profession = "Developer"
}.printPerson()
}
data class Person(var name: String, var age: Int, var profession: String) {
//fun printPerson() = println(this.toString())
}
fun Person.printPerson() = println(toString())
fun String.println() = println(this)
fun Int.println() = println(this)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment