Kotlin Scope Functions and their use

As you know kotlin is the official language for Android Development since 2017.

Kotlin provides the way in which we can write clear code and make it easy to understand.

So, today we will discuss one of the main features of koltin which is known as Scope Functions

There are basically five scope functions in kotlin which are :

  1. i) let
  2. ii) run 

iii) with

  1. iv) apply
  2. v) also

There are basically two differences between these functions:

  1. i) we refer to the object’s value with the help of “it” or “this” keyword. 
  2. ii) these functions return either “context object” or “lambda result”.

Every function has its own value which we will discuss in detail with their respective examples.

  • let
  1. i) object value = it
  2. ii) return value = lambda result

So, basically, we use the “let” function for avoiding NullPointerException and we use the null safe operator ?. for calling. The piece of code will execute only when the value is not null.

Eg :

 

So, in the above example, you can see when a is null then the code will not enter into the let block and if a is not null then the let block will execute. So, this states that we use the let function to avoid NullPointerException.

  • apply
  1. i) object value = this
  2. ii) return value = context object

So, basically, the “apply” function is mostly used for the initialization of data members of the class.

For eg :

 

So, in the above example, you can see we don’t have to always initialize members with the help of object (student.name = “Kotlin”). Kotlin’s “apply” function is easy to use and also easy to understand.

  • with
  1. i) object value = this
  2. ii) return value = lambda result

Here, Kotlin “with” function is basically used for getting the value of data members with the help of object reference

For eg: 

 

So, in the above example, you can see we don’t have to use references always for printing values (like println(“$student.name”)).

You can easily remove this dependency with the help of with() function.

  • run
  1. i) object value = this
  2. ii) return value = lambda result

The run function is basically a combination of “let” and “with” which means we can check for null and also get the values.

For eg : 

 

  • also 
  1. i) object value = it
  2. ii) return value = context object

It is basically used for further operations we want to perform on members.

For eg : 

 

So, in the above example, you can see we can perform additional operations after initializing it.

So, this is all about Kotlin Scope Functions

For more information go to https://kotlinlang.org/docs/scope-functions.html

Leave a Reply