KOTLIN: Scope Functions ๐

Being in love with coding, I'm looking for opportunities to utilize and grow my technical abilities as a programmer (full stack developer, frontend or backend )
In Kotlin, the scope functions are a set of functions that allow you to perform operations on an object within a specific scope. These functions are often used to simplify and enhance the readability of the code when working with objects, particularly in scenarios where we need to execute multiple operations on an object or perform some initialization steps.
There are five main scope functions in Kotlin:
let: The
letfunction allows you to execute a block of code on an object and returns the result of the block as the result of theletfunction. It's commonly used for performing operations on an object and returning a modified result.
run: The
runfunction is similar tolet, but it operates on the object itself instead of providing it as a parameter to the block. It returns the result of the block.
with: The
withfunction is used to call multiple methods on an object without the need to reference the object explicitly. It doesn't return a result; instead, it allows you to write code more concisely.
apply: The
applyfunction is used for performing initialization on an object or configuring its properties. It returns the object itself after applying the operations.
also: The
alsofunction is similar toapply, but it returns the object itself rather than the result of the block. It's often used for side effects or additional actions on an object.
How to Distinguish between Scope Function
The way to refer to the context object ( Either "this" or "it" keyword )
The return values ( Either "context object" or the "lambda result" )

Summary
with:
if you want to operate on a non-null objectlet:
If you want to just execute lambda expression on a nullable object and avoid NullPointerExceptionrun:
If you want to operate on a nullable object, execute lambda expression and avoid NullPointerException, it is the combination of the 'let' function and 'with' functionapply:
If you want to initialise or configure an objectalso:
If you want to do some additional object configuration or operations
Wow great you have made it to the end ๐. Thank you so much for your patient and for taking crucial time for my article hope you got a good understanding of above mentioned topics and I will see you in my next article !!!
Peaceโ๏ธ Happy Coding ๐จ๐ปโ๐ป



