Skip to content

Instantly share code, notes, and snippets.

@prokash-sarkar
Created September 15, 2019 06:33
Show Gist options
  • Save prokash-sarkar/b36d547ca06445690414b7302322ddd4 to your computer and use it in GitHub Desktop.
Save prokash-sarkar/b36d547ca06445690414b7302322ddd4 to your computer and use it in GitHub Desktop.
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