Kotlin Scoped functions

Almost all the Android developers either have moved or are moved from using Java to Kotlin and are experiencing how clean, simple, and concise Kotlin is when contrasted to Java. Kotlin brings in the market a bunch of developer-friendly features for less code, thereby resulting in fewer bugs.

Among the many developer-friendly features, Kotlin brings, “scope functions” are one of the most crucial features. If you have adequate hands-on experience, you might be already using scope functions. Or, if you find this topic totally new and want to understand these scoped functions? Well, in that case, let’s dive into the article.

Scoped Functions in Kotlin

As per standard definition, Scoped functions are functions that execute a block of code within the context of an object.

The benefit of using scope functions​

Scope functions make code more clear, readable, and concise which are Kotlin language’s main features. It skips the block if the object is null.

Types of scope functions

There are five scoped functions in Kotlin: 

  • Let
  • Run
  • With
  • also
  • apply

Let’s discuss them one by one with simple examples. These functions provide a context to an object (it or this) and return type (object or lambda result).

What is Lambda Result?

A lambda function is a small function, which takes any number of arguments, but can only have one expression.
But before going through these examples, let’s consider a class “Employee”
Class Employee(var empId:Int?=null, 
var empName:String?=null, 
var empDesignation:String?=null)

Android Developer

1. let function

Context object  : it (you can rename it) ||  Return value    :  
lambda result
When to use:
let function is used to avoid null calls. Use safe call operator(?.) with ‘let’ for null safety. It executes the block only if the object or variable is non-null.

2. Apply function

Context object: this 
||  Return value    : context object
When to use:
As the name indicates – “Apply these to the object.” It is mainly used to initialize/assign values to members of an object of the class.

Example:
Employee().apply{
this.empId=101,
empName=”Razia”
empDesignation=”Android Lead”
}

3. With function

Context object  : this 
||  Return value    : lambda result

When to use: 
The use of “with” is similar to the “let” and “run” function; the difference is: “with” does not ignore the null value. Another way of glimpsing it is as logically grouping multiple calls to a given object:

Example:
with(employee) {
   println(" $empName ")
printInfo(...)
calculateSalary(...) }

4. Run function

Context object  : this 
||  Return value    : lambda result
The “run” function is the combination of ‘let’ and ‘with’ functions.

When to use:
“run” is used when the object lambda contains initialization and the computation of the return value. Using run, we can perform null safety calls. It ignores the block if the object is null.

Example:
   val name = Employee().empName?.run {
        "The name of the Person is: $this"
    }
    print(name)

Output:
The name of the Person is: Razia

5. Also function

Context object  : it || 
Return value    : 
context object 
When to use:
“also,” as the name indicates, needs to add some stuff. This is used when you need to perform some additional operations and provide null safety checks:

Example:
 val name = Employee().also { employee->
print("Current name is: ${employee.empName}\n")
employee.empName = "Razia Sharma"
}.run {  
"Modified name is: $name\n"
    }
print(name)
}

Output:
Current name is: Razia
Modified name is: Razia Sharma

It’s time to conclude about the Scoped functions in Kotlin. Even though we might be using it in our coding, we really hope that our article has provided you with a better way of understanding and implementing the right scoped function in the right place.
Thank you so much for your time!