0
0
Kotlinprogramming~5 mins

With function behavior and use cases in Kotlin

Choose your learning style9 modes available
Introduction

The with function helps you run many operations on the same object without repeating its name. It makes your code shorter and easier to read.

When you want to call multiple functions or access properties on the same object.
When you want to group related operations on an object to improve code clarity.
When you want to avoid repeating the object name many times in your code.
When you want to perform setup or configuration steps on an object in one place.
Syntax
Kotlin
with(object) {
    // code block where 'this' refers to object
    // call functions or access properties
}

The object is passed as the first argument to with.

Inside the block, this refers to the object, so you can call its methods directly.

Examples
Prints the name and age of the person without repeating person.
Kotlin
val person = Person("Anna", 25)
with(person) {
    println(name)
    println(age)
}
Builds a string by calling append multiple times on the same StringBuilder object.
Kotlin
val builder = StringBuilder()
with(builder) {
    append("Hello")
    append(" World")
    println(toString())
}
Sample Program

This program creates a Person object and uses with to print and update its properties easily.

Kotlin
data class Person(var name: String, var age: Int)

fun main() {
    val person = Person("John", 30)
    with(person) {
        println("Name: $name")
        println("Age: $age")
        age += 1
        println("Happy Birthday! New age: $age")
    }
}
OutputSuccess
Important Notes

with is not an extension function; it takes the object as an argument.

Use with when you want to perform multiple operations on an object but don't need to return a value from the block.

If you want to return a value, consider using run instead.

Summary

with helps write cleaner code by grouping operations on one object.

Inside the with block, you can call methods and access properties directly.

It is useful for setup or multiple calls on the same object without repeating its name.