kotlin scope functions code example

Example 1: kotlin scope functions

| 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: kotlin scope functions

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

Example 3: function kotlin

// Declare a function in Kotlin
fun happyBirthday(name: String, age: Int): String {
    return "Happy ${age}th birthday, $name!"
}
// Call function
val greeting = happyBirthday("Anne", 32)

Tags:

16 Example