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.
With function behavior and use cases in 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.
person without repeating person.val person = Person("Anna", 25) with(person) { println(name) println(age) }
append multiple times on the same StringBuilder object.val builder = StringBuilder() with(builder) { append("Hello") append(" World") println(toString()) }
This program creates a Person object and uses with to print and update its properties easily.
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") } }
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.
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.
Practice
with function in Kotlin?Solution
Step 1: Understand the role of
Thewithwithfunction groups multiple calls on the same object, so you don't repeat the object name.Step 2: Compare with other options
Options A, B, and D describe unrelated Kotlin features like class definition, threading, and exception handling.Final Answer:
To execute multiple operations on the same object without repeating its name -> Option CQuick Check:
withgroups calls on one object = C [OK]
with avoids repeating object name [OK]- Confusing
withwith threading or concurrency - Thinking
withcreates new classes - Assuming
withhandles exceptions
with in Kotlin?Solution
Step 1: Recall the syntax of
The correct syntax iswithwith(object) { /* code block */ }, where the object is passed as an argument and the block follows in braces.Step 2: Identify incorrect syntax
Options B, C, and D misuse arrow notation or omit parentheses, which are syntax errors.Final Answer:
with(object) { /* code block */ } -> Option AQuick Check:
Correctwithsyntax uses parentheses and braces = A [OK]
with [OK]- Omitting parentheses around the object
- Using arrow notation incorrectly
- Placing the block outside braces
data class Person(var name: String, var age: Int)
fun main() {
val person = Person("Alice", 25)
val result = with(person) {
age += 1
"${name} is now $age years old"
}
println(result)
}Solution
Step 1: Analyze the
Thewithblock behaviorwithfunction usespersonas the context. Inside,ageis incremented by 1, changing it from 25 to 26.Step 2: Evaluate the returned string
The last expression in the block is the string interpolation "${name} is now $age years old", which becomes "Alice is now 26 years old".Final Answer:
Alice is now 26 years old -> Option DQuick Check:
Age incremented insidewith= D [OK]
with is the return value [OK]- Forgetting that age is incremented inside
with - Thinking string interpolation causes error
- Assuming modifying properties causes runtime error
with:
fun main() {
val list = listOf(1, 2, 3)
with(list) {
add(4)
println(this)
}
}Solution
Step 1: Check the list type and mutability
The list is created withlistOf, which returns an immutable list that does not supportadd.Step 2: Understand the error cause
Callingadd(4)on an immutable list causes a compile-time error because the method is not available.Final Answer:
Cannot calladdon an immutable list -> Option AQuick Check:
Immutable list blocksaddmethod = A [OK]
- Assuming
withchanges mutability - Thinking
thisis incorrect insidewith - Ignoring immutability of
listOf
with to increase all scores by 5 points and return the updated map?
Choose the correct Kotlin code snippet.Solution
Step 1: Understand map mutability and
The map is mutable, so we can update values by keys insidewithusagewith. with(students) { for (key in keys) this[key] = this[key]!! + 5; this } correctly loops keys and updates values.Step 2: Analyze other options for correctness
with(students) { keys.forEach { it += 5 }; this } tries to add 5 to keys (strings), which is invalid. with(students) { mapValues { it.value + 5 } } returns a new map but does not update original. with(students) { forEach { it.value += 5 }; this } tries to modifyit.valueinforEach, but map entries are immutable in this context.Final Answer:
with(students) { for (key in keys) this[key] = this[key]!! + 5; this } -> Option BQuick Check:
Update map values by keys insidewith= B [OK]
with [OK]- Trying to modify keys instead of values
- Assuming
mapValuesmutates original map - Modifying map entries directly in
forEachcauses error
Ready to prove it?
Pass the test and this pattern moves unknown
