Friday, June 9, 2023

What is Scope Function in Kotlin? Difference between Scope Functions: let, run, with, apply, also.

What is Scope Function in Kotlin?



In Kotlin, the scope function is not a built-in function. However, there are several scope functions available in Kotlin that help in defining a temporary scope for an object, allowing you to perform operations on it without the need to create intermediate variables. These scope functions are: let, run, with, apply, and also. Check the youtube video

Linked In

Here's a brief overview of each scope function:


let: It allows you to execute a block of code on a non-null object and returns the result of the block. Within the block, the object is accessible using the it keyword.

val data = "Sample"
val result = data.let {
// Perform operations on it
// Return the result
val level = data + "One"
level.substring(0,1)
}

 

  • Context Object : 'it'
  • Return Value : Lambda result


 with: It is similar to run, but the object is passed as a parameter to the function instead of being accessed through a receiver. It does not return any result.
val data = "Sample"
with(data) {
// Perform operations on it
// Return the result
val level = data + "One"
level.substring(0,1)
}

 

  • Context Object : 'this'
  • Return Value : Lambda result


 run: It is similar to let, but the object is accessed through the this keyword within the block. It returns the result of the block.
val data = "Sample"
val result = data.run {
// Perform operations on it
// Return the result
val level = data + "One"
level.substring(0,1)
}

 

  • Context Object : 'this'
  • Return Value : Lambda result


 apply: It allows you to configure the properties of an object and returns the object itself. The object is accessed using the this keyword within the block.
val intent = Intent().apply { 
putExtra("Type", "user")
putExtra("Value", "normal")
setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
}
startActivity(intent)

 

  • Context Object : 'this'
  • Return Value :  Context Object


 also: It is similar to apply, but it does not return the object itself. Instead, it returns the original object. It is often used for performing additional actions on an object, such as logging or side effects.

val intent = Intent().also {
it.putExtra("Type", "user")
it.putExtra("Value", "normal")
it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
}
startActivity(intent)


  • Context Object : 'it'
  • Return Value :  Context Object




Thank you for reading this blog. Hope this will be use full to you. Follow for more blog like this.




















Comparision of android native xml UI components and the Getpack UI components

Certainly I want to see side by side how the old android native xml UI components and the Getpack UI components.  if you guys are started le...