Kotlin Q & A

 

What is the with function in Kotlin?

The with function in Kotlin is a convenient tool used to operate on an object within a specific context without the need for repetitive references to the object. It provides a concise and expressive way to perform multiple operations on an object by temporarily changing the scope to the object itself.

The with function is not an extension function; instead, it is a standard library function defined in the Kotlin standard library.

Here’s a simplified example demonstrating the usage of the with function:

kotlin

class Person {
 var name: String = ""
 var age: Int = 0
}

val person = Person()

with(person) {
 name = "John"
 age = 30
}

In this example, the with function is called on the person object. Within the lambda passed to with, properties of the person object (name and age) are modified directly. The with function simplifies the code by allowing direct access to properties of the person object within its scope.

The primary advantage of the with function lies in its ability to improve code readability and maintainability by eliminating repetitive references to the same object. It is commonly used in scenarios where multiple operations need to be performed on an object within a specific context.

Previously at
Flag Argentina
Brazil
time icon
GMT-3
Experienced Android Engineer specializing in Kotlin with over 5 years of hands-on expertise. Proven record of delivering impactful solutions and driving app innovation.