kotlin apply example

Example 1: kotlin also

| Function | Object reference | Return value   | Is extension function                        |
|----------|------------------|----------------|----------------------------------------------|
| let      | it               | Lambda result  | Yes                                          |
| run      | this             | Lambda result  | Yes                                          |
| run      | -                | Lambda result  | No: called without the context object        |
| with     | this             | Lambda result  | No: takes the context object as an argument. |
| apply    | this             | Context object | Yes                                          |
| also     | it               | Context object | Yes                                          |

Example 2: apply in kotlin

fun main(args: Array) 
{ 
    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) 
}

Example 3: kotlin scope functions

| object  lambda
-----+----------------
this | apply    run
it   | also     let

Example 4: kotlin apply

return EditAccessoryFragment().apply {
    arguments = bundleOf(ACCESSORY_ID_LABEL to accessoryID)
}

Tags:

Misc Example