How to Use with Function in Kotlin: Simple Guide
In Kotlin, the
with function lets you call multiple methods or access properties on the same object without repeating its name. You pass the object and a block of code where you can use its members directly, making your code cleaner and easier to read.Syntax
The with function takes two parts: the object you want to work with, and a block of code where you can call the object's methods or properties directly.
Syntax:
with(object) {
// code using object members
}Inside the block, this refers to the object, so you don't need to repeat the object name.
kotlin
with(receiverObject) {
// use receiverObject's methods or properties here
}Example
This example shows how to use with to print details of a StringBuilder object without repeating its name.
kotlin
fun main() {
val sb = StringBuilder()
with(sb) {
append("Hello")
append(", ")
append("Kotlin!")
println(toString())
}
}Output
Hello, Kotlin!
Common Pitfalls
One common mistake is trying to use with when you need to return a value from the block. with returns the last expression, but if you don't use it properly, you might ignore the result.
Also, avoid using with on null objects, as it will cause a NullPointerException.
kotlin
fun main() {
val list = listOf(1, 2, 3)
// Wrong: ignoring the return value of with
with(list) {
println(size)
}
// Right: using the return value
val size = with(list) {
size
}
println("Size is $size")
}Output
3
Size is 3
Quick Reference
- Purpose: Call multiple methods on the same object without repeating its name.
- Returns: The last expression inside the block.
- Receiver: The object passed as the first argument.
- Use case: Simplify code readability.
Key Takeaways
Use
with to call multiple methods on one object without repeating its name.with returns the last expression inside its block, so you can capture results.Avoid using
with on null objects to prevent errors.Inside
with, this refers to the object, allowing direct access to its members.Use
with to make your code cleaner and more readable when working with one object.