What if you could stop repeating the same object name over and over and make your code look neat and simple?
Why With function behavior and use cases in Kotlin? - Purpose & Use Cases
Imagine you have an object, and you want to call several functions or access many properties on it one by one. You write the object name every time, like user.name, user.age, user.address. It feels like repeating yourself a lot.
This manual way is slow and tiring. You might make mistakes typing the object name repeatedly. It clutters your code and makes it harder to read and understand what you are doing with the object.
The with function lets you group all those calls inside a block where you just write the object once. Inside the block, you can access the object's properties and functions directly, making your code cleaner and easier to follow.
println(user.name) println(user.age) println(user.address)
with(user) {
println(name)
println(age)
println(address)
}With the with function, you write less code and focus on what you want to do with the object, making your programs simpler and more readable.
When you work with a Person object and want to print or update many details like name, age, and email, with helps you do it neatly without repeating the object name each time.
with reduces repetition by letting you call multiple functions or properties on the same object inside a block.
It makes your code cleaner and easier to read.
It helps avoid mistakes from typing the object name many times.