Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin | apply vs with

apply and with are two Kotlin standard library functions that are used to operate on objects within a lambda. They might seem similar, but they have distinct use cases and behaviors. Here's a breakdown:

1. with:

  • Receiver: Uses the object passed as an argument.
  • Return value: Returns the lambda result.
  • Typical use case: When you have an object (which might not be nullable) and you want to perform a series of operations on it and then return a result.

Example:

val result = with(StringBuilder()) {
    append("Hello")
    append(", ")
    append("World!")
    toString()
}
print(result)  // Outputs: Hello, World!

2. apply:

  • Receiver: Uses the object on which it's invoked (i.e., the receiver).
  • Return value: Returns the object it's invoked on (i.e., the receiver).
  • Typical use case: When you have an object and you want to modify it in some way and then continue working with that object.

Example:

val myStringBuilder = StringBuilder().apply {
    append("Hello")
    append(", ")
    append("Kotlin!")
}
print(myStringBuilder.toString())  // Outputs: Hello, Kotlin!

Comparison:

To demonstrate the difference:

val list = mutableListOf(1, 2, 3)

val resultWith = with(list) {
    add(4)
    size  // Returns the size as the result of the lambda
}
println(resultWith)  // Outputs: 4

val resultApply = list.apply {
    add(5)
    add(6)
    // Doesn't return anything from the lambda. The list itself will be returned.
}
println(resultApply)  // Outputs: [1, 2, 3, 4, 5, 6]

Key Takeaways:

  • Use with when you want to perform operations on an object and return some result from the lambda.

  • Use apply when you want to make modifications to an object and then return the object itself.

Remember, the primary goal of these functions is to help make the code more readable and expressive. Always consider the readability of your code when deciding to use them.

  1. apply vs with in Kotlin examples:

    val person = Person().apply {
        name = "John"
        age = 30
    }
    
    with(person) {
        println("Name: $name, Age: $age")
    }
    
  2. Kotlin apply function explained:

    • apply is an extension function that operates on the context object and returns the same object.
    • It is often used for initializing or configuring properties of an object.
    val person = Person().apply {
        name = "John"
        age = 30
    }
    
  3. Kotlin with function use cases:

    • with is used when you want to perform operations on an object within a block without modifying its properties.
    • It enhances code readability by removing redundant references to the object.
    with(person) {
        println("Name: $name, Age: $age")
    }
    
  4. Scenarios for applying apply in Kotlin:

    • Configuring properties of an object during its creation.
    • Setting up or initializing an object's state.
    val car = Car().apply {
        brand = "Toyota"
        model = "Camry"
        year = 2022
    }
    
  5. Kotlin apply vs also comparison:

    • also is similar to apply but returns the original object instead of the context object.
    • apply is more suitable for property configuration during object creation.
    val person = Person().also {
        it.name = "John"
        it.age = 30
    }
    
  6. Using with for concise code in Kotlin:

    • with can be used to make code more concise by avoiding repeated references to the object.
    with(person) {
        eat()
        sleep()
    }