Skip to main content

Command Palette

Search for a command to run...

KOTLIN: Scope Functions ๐Ÿ”

Updated
โ€ข2 min read
KOTLIN: Scope  Functions ๐Ÿ”
P

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:

  1. let: The let function allows you to execute a block of code on an object and returns the result of the block as the result of the let function. It's commonly used for performing operations on an object and returning a modified result.

  2. run: The run function is similar to let, but it operates on the object itself instead of providing it as a parameter to the block. It returns the result of the block.

  3. with: The with function 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.

  4. apply: The apply function is used for performing initialization on an object or configuring its properties. It returns the object itself after applying the operations.

  5. also: The also function is similar to apply, 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 object

let: If you want to just execute lambda expression on a nullable object and avoid NullPointerException

run: 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' function

apply: If you want to initialise or configure an object

also: 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 ๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ป