Kotlin: Scope Functions

Divyasourabh
2 min readAug 11, 2020

Scope functions are functions that execute a block of code within the context of an object.

Scope functions provides a way to give temporary scope to the object, where specific operations can be applied to the object within the block of code.

Scope functions make your code more concise and readable.

There are five scoped functions in Kotlin: let, run, with, also and apply.

Transformation functions that takes an A and returns a B.

Mutation functions that takes an A mutates its state and returns it back.

Scope functions are similar in nature so it is important to understand the difference between them. There are two main differences between each scope function:

  • Context object they are refer to
  • What they return.

let and also refer to ‘it’ reference which can be rename to meaningful name and run, with, apply refer to ‘this’ reference which cannot be rename.

class Student() {
var name: String = "XYZ"
var className
: String = "10"

fun
printStudentDetails(){
print("Student Name: $name Student Class: $className")
}
}
private fun showingHowRenameContextObject() {
val student = Student().let { studentDetails ->
studentDetails.name = "xyz"
studentDetails.className="12"
}
print("Student Name : $student.name")
}
output: Student Name : xyz

let, run, with return result of lambda expressions (set of block code) so we can use them when assigning the result to a variable, chaining operations,and so on. Also you can ignore the return value and use a scope function to create a temporary scope for variables. Example we can use them as a initialization block.

private fun showingHowLetWorks() {
val stringToPrint= Student().let {studentDetails->
return "The name of the Student is: ${
studentDetails.name}"
}
print(stringToPrint)
}
output: The name of the Student is: xyz

also, apply return value is the context object itself.

private fun showingApplyWorks() {
val student: Student? = null
student?.apply {
name
= "abcd"
className
= "10"
printStudentDetails()
}
}
output: Student Name: abcd Student Class: 10

Scope functions are higher-order functions for standard Kotlin library.

Thanks for reading this article. Be sure to click 👏 below to applause this article if you found it helpful. It means a lot to me.

Other Important Link

--

--