Skip to content
Related Articles

Related Articles

Improve Article

Kotlin | apply vs with

  • Last Updated : 09 Aug, 2019

Kotlin :: apply

In Kotlin, apply is an extension function on a particular type and sets its scope to object on which apply is invoked. Apply runs on the object reference into the expression and also returns the object reference on completion. It does not simply setting properties of course but do much more functionalities and capable of evaluating complex logic before returning. In the end, it returns the same object, with some modified changes.

  • apply is an extension function on a type.
  • It requires an object reference to run into an expression.
  • It also return an object reference on completion.
  • Definition of apply :

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

    Example of apply




    fun main(args: Array<String>)
    {
        data class GFG(var name1 : String, var name2 : String,var name3 : String)
        // instantiating object of class
        var gfg = GFG("Geeks","for","hi")
        // apply function invoked to change the name3 value
        gfg.apply { this.name3 = "Geeks" }
        println(gfg)
    }

    Output :

    GFG(name1=Geeks, name2=for, name3=Geeks)
    

    Here the 3rd member of class GFG is changed from “hi” to “Geeks”.



    Kotlin :: with

    Like apply, with is also used to change properties of an instance. But here we don’t require a object reference to run, i.e. : we don’t need a dot operator for reference.


    Definition of with

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

    Example of with




    fun main(args: Array<String>)
    {
        data class GFG(var name1: String, var name2 : String,var name3 : String)
        var gfg = GFG("hello", "for","hi")
        // applying with function
        with(gfg)
        {
            name1 = "Geeks"
            name3 = "Geeks"
        }
        println(gfg)
    }

    Output :

    GFG(name1=Geeks, name2=for, name3=Geeks)
    

    Here we don’t require any dot operator, and we changed the values of first and third variables of an object of class GFG using with extension function.

    Difference between apply and with

  • with runs without an object whereas apply needs one object to run
  • apply runs on the object reference, but with simply passes it as the argument



  • My Personal Notes arrow_drop_up
    Recommended Articles
    Page :