Kotlin Tutoial
Basics
Control Flow
Array & String
Functions
Collections
OOPs Concept
Exception Handling
Null Safety
Regex & Ranges
Java Interoperability
Miscellaneous
Android
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:
with
:Example:
val result = with(StringBuilder()) { append("Hello") append(", ") append("World!") toString() } print(result) // Outputs: Hello, World!
apply
:Example:
val myStringBuilder = StringBuilder().apply { append("Hello") append(", ") append("Kotlin!") } print(myStringBuilder.toString()) // Outputs: Hello, Kotlin!
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]
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.
apply vs with in Kotlin examples:
val person = Person().apply { name = "John" age = 30 } with(person) { println("Name: $name, Age: $age") }
Kotlin apply function explained:
apply
is an extension function that operates on the context object and returns the same object.val person = Person().apply { name = "John" age = 30 }
Kotlin with function use cases:
with
is used when you want to perform operations on an object within a block without modifying its properties.with(person) { println("Name: $name, Age: $age") }
Scenarios for applying apply in Kotlin:
val car = Car().apply { brand = "Toyota" model = "Camry" year = 2022 }
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 }
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() }