let{} and run{} Scope fun

let{} and run{} Scope fun

Good morning fellow developers ,

Let's grab a cup a coffee and recall a functional feature and type of functions as a feature , named as Scope functions .

This Scope function are the functions which uses temporary scope of any object to manage and perform any operation using the context of that object as a reference ,these are made mainly to resolve the daily hardships we are facing like readability, maintainability , to make code more concise(less vocabulary) , efficient object handling etc....

As an old , there are five type's of scope functions mainly ,

  1. let{}
  2. run{}
  3. with(object){}
  4. apply{}
  5. also{}


All the scope functions which is mentioned above have different purpose and slightly different use case ,even they look somewhat similar though ,

let{} scope function

  • with the use of object , this fun uses it (or) any named reference to declare context of that particular object . And perform operation along with that.
  • Example,


var name = "Praveen Selvakumar";

    name.let{
        println(it)
    }
    //OR
    name.let { myName ->
        println(myName)
    }        

Use Case

  • let is mainly used to ensure an object which is not null .
  • Example ,

object?.let{
  //perform  any operations
}        

above example will be promising if you are handling with any nullable objects.


run{} scope function

  • with or without use of object , this fun assist us to manage or modify or do any operation in the object or in common . It use this as reference or empty reference to access the context .
  • Example ,

//WITHOUT OBJECT REFERENCE  
run {
        println(name)
    }
    //OR

//WITH OBJECT REFERENCE 
    name.run {
        println(this)
    }        

Use Case

  • Used for binding the view , return the value by performing any operation or clear segregation of any object , perform multiple operation and return single result .
  • Example,

 //CONSIDER OBJECT IS A STRING
object.run {
   print(object)
}

object.run{
 this = "another value"
}

object.run{
 this.plus(" Selva kumar")
}

//etc...        

We have even more example using let and scope let's discuss it more detail on upcoming article.

Thank you.

要查看或添加评论,请登录

Praveen Selvakumar的更多文章

  • with(){}, apply{} and also{} Scope fun

    with(){}, apply{} and also{} Scope fun

    Good morning fellow developers , Let's continue from the previous article. Now, we'll discuss the three functions we…

社区洞察

其他会员也浏览了