Kotlin - apply vs with

We will discuss Apply vs with, In this tutorial

Apply :

Apply is an extension of a function in the set scope of the object in which apply is invoked. Apply runs on the object reference of expression and also returns object reference. Apply function works on complex logic before returning of Mobile application.

Syntax:

 inline fun  T.apply(block: T.() -> Unit): T 
 {
     return this
 }

Example of Apply:

 fun main(args: Array<String>)
{
    data class demo(var one : String, var two : String)
    var demodata = demo("Hello","How are you?")
    demodata.apply { this.one = "Fine" }
   println(demodata)
}

 Output

   demo(one=Fine, two=How are you?)

With :

With is another tool for altering an instance's characteristics, just like apply. Here, however, an object is not necessary.

Syntax:

  inline fun  with(receiver: T, block: T.() -> R): R 
 {
    return receiver.block()
 }

Example of with

   fun main(args: Array<String>)
  {
    data class demo(var one: String, var two : String)
    var result = demodata("hello", "for")
    with(result)
    {
           one = "Fine"
           two = "Thank you"
      }
     println(result)
  }

Output

   demo(one=Fine, two=Thank you)

Happy coding!

365Bloggy June 18, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive