Skip to content

Kotlin scope functions

Devrath edited this page Dec 24, 2023 · 2 revisions

840cee8b164c10b

In Kotlin, scope functions (let, also, apply, run, and with) are used to define a scope for a block of code and can be helpful in making code more concise and readable. Each scope function has its own use cases and is suitable for different scenarios. Here's a brief overview of each:

  1. let: Use let when you want to perform some operations on a non-null object and return a result. It is often used for chaining function calls on a single object.

    val result = someNullableObject?.let {
        // Code to be executed if someNullableObject is not null
        it.doSomething()
    }
  2. also: Use also when you want to perform additional actions that don't affect the object itself. It returns the original object.

    val result = someObject.also {
        // Code to be executed on someObject without modifying it
        log.info("Processing $it")
    }
  3. apply: Use apply when you want to initialize or configure an object. It returns the receiver object, allowing you to modify its properties inside the block.

    val someObject = SomeClass().apply {
        // Code to initialize or configure someObject
        property1 = "value1"
        property2 = "value2"
    }
  4. run: Use run when you need to execute a block of code on a non-null object and return a result. It's similar to let, but it operates on the context of the object itself.

    val result = someObject?.run {
        // Code to be executed on someObject if it is not null
        doSomething()
    }
  5. with: Use with when you want to operate on an object without the need to use its name repeatedly. It is an extension function and does not return a value.

    with(someObject) {
        // Code to be executed on someObject without repeating its name
        doSomething()
        doAnotherThing()
    }

In summary, choose the scope function based on your specific use case. If you need to perform operations on a non-null object and return a result, consider using let or run. If you want to perform additional actions without modifying the object, use also. For object initialization or configuration, use apply. If you want to operate on an object without repeating its name, use with.

Clone this wiki locally