Read More

Kotlin Scope Functions

Kotlin Scope Functions are basically provided to manage the variable scopes easily. These are designed in a way that you can access the variables without even using their names again and again and also you don’t need to manage their scopes. You can definitely check the official doc.

Let’s take an example

Support, we have a class that has few variables in it.

As you can see above. If I want to access the variable from this class then I would have to create its object and use its identifier. The below-given code will help you with that.

As you can see we, again and again, writing the studentModel identifier to access each property.

Here the Kotlin Scope Functions come to rescue. Let’s see one by one each of them.

1. let

The object is represented by the argument (it). It returns the last statement of the lambda expression.

2. with

The object is available as a receiver (this). It returns the last statement of the lambda expression.

3. run

The object is available as a receiver (this). It returns the last statement of the lambda expression.

You can execute several statements with the run.

4. apply

The object is available as a receiver (this). It returns the object itself.

5. also

The object is available as an argument (it). It returns the object itself.

And the main feature of all of these functions is that you don’t need to think about the object that has been created. The will be automatically destroyed as soon as the scope function completes.

That’s all for this blog. Thank you very much. This is Vedesh Kumar signing off.

 

. . .

Comment

Add Your Comment

Be the first to comment.

css.php
Hire Us!
Brief us about your requirements and we'll get back to you.
Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again
Close