Scope Function in Kotlin

What is Scope Function?

Scope Function execute a block of code within context of object.That is if you perform this function on an object inside an lambda expresssion then the scope inside the expression will be executed that is called Scope Function

Types Of Scope Function

let → we use this often when we want to execute any operation on not null values by using safe call operator ?.

Always let refer the context of object by using it and return lambda result as an return value

We can pass any local variable inside the scope for the replacement of it so its easy readable

Sample Program on let:

In the above example it wont execute the let function if the name value is null

In the above example output is 8

run → Used when the object lambda contains both initialization and the computation of the return value. Using run we can perform null safety calls as well as other computations.

with → It takes context of object as an argument and perform operation on it

It refer the context of object by using this and return lambda result as an return value

We can perform not null operation here but we have to give not null assertion on each line which doesn't look nice

apply → As the name implies “apply on the object” it refer the context of object by using this and return the context object itself its is mainly used for initialize the members.

also → It will be used when we want to do any additional operation after initialization of member and it refer the context of object by using it and return context object itself

Knowledge is everything.Check out my app at https://play.google.com/store/apps/details?id=com.vibe.britevibe

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

CheerpX: Using WebAssembly to run any programming language in the browser

Performance of ‘=’ vs ‘like’ in SQL 🤔

Shapley value, how to understand

AI, ethics and the AWS container strategy comes around

Union find or DFS/BFS

10 advanced Joomla tips to become a pro

A brief introduction about CLSID and a bypass found

Building a Raspberry Pi Web Server

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pandiyan Mani

Pandiyan Mani

Knowledge is everything.Check out my app at https://play.google.com/store/apps/details?id=com.vibe.britevibe

More from Medium

Manual CoroutineScopes: how to avoid GlobalScope

Zip, combineLatest, debounce etc in Coroutines?

Kotlin Flows: The Graduated Coroutine — I

Network call with kotlin coroutines