What is the purpose of the with function in Kotlin?
The with function is used to call multiple methods or access properties on the same object without repeating the object name. It helps make code cleaner and easier to read.
Click to reveal answer
beginner
How does the with function improve code readability?
It allows you to write code inside a block where the object is the receiver, so you don't need to repeat the object name for each call. This reduces clutter and makes the code look simpler.
Click to reveal answer
intermediate
What is the return value of the with function?
The with function returns the result of the last expression inside its block.
Click to reveal answer
beginner
Show a simple example of using with to configure a StringBuilder.
Example:
val result = with(StringBuilder()) {
append("Hello")
append(", ")
append("World!")
toString()
}
// result is "Hello, World!"
Click to reveal answer
intermediate
When should you use with instead of apply or run?
Use with when you want to perform multiple operations on an object and return a value from the block, but you don't want to call it as an extension function. apply returns the object itself, and run is an extension function that returns the block result.
Click to reveal answer
What does the with function take as its first argument?
AA Boolean condition
BA lambda with receiver
CA list of objects
DAn object to operate on
✗ Incorrect
The with function takes an object as its first argument and then a lambda block to operate on that object.
Inside the with block, how do you refer to the object passed in?
AUsing <code>this</code> as the receiver
BUsing the object name explicitly
CUsing <code>it</code>
DUsing a global variable
✗ Incorrect
Inside the with block, the object is the receiver, so you can call its methods and properties directly using this implicitly.
What does with return?
AThe object passed in
BThe last expression inside the block
CAlways <code>Unit</code>
DA Boolean value
✗ Incorrect
The with function returns the value of the last expression inside its block.
Which of these is a typical use case for with?
AFiltering a list
BCreating a new object
CConfiguring an object with multiple method calls
DRunning code asynchronously
✗ Incorrect
with is often used to call multiple methods on the same object to configure or build it.
How is with different from apply?
A<code>with</code> is not an extension function, <code>apply</code> is
B<code>with</code> returns the object, <code>apply</code> returns last expression
C<code>with</code> works only with strings, <code>apply</code> works with any object
DThere is no difference
✗ Incorrect
with is a regular function taking the object as an argument, while apply is an extension function called on the object.
Explain how the with function works in Kotlin and give an example of when you might use it.
Think about how you can avoid repeating the object name when calling multiple methods.
You got /4 concepts.
Compare with to apply and run in Kotlin. When would you choose with?
Focus on how each function is called and what they return.
You got /3 concepts.
Practice
(1/5)
1. What is the main purpose of the with function in Kotlin?
easy
A. To define a new class inside a function
B. To create a new thread for concurrent execution
C. To execute multiple operations on the same object without repeating its name
D. To handle exceptions in a concise way
Solution
Step 1: Understand the role of with
The with function 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 C
Quick Check:
with groups calls on one object = C [OK]
Hint: Remember: with avoids repeating object name [OK]
Common Mistakes:
Confusing with with threading or concurrency
Thinking with creates new classes
Assuming with handles exceptions
2. Which of the following is the correct syntax to use with in Kotlin?
easy
A. with(object) { /* code block */ }
B. with { object -> /* code block */ }
C. with object { /* code block */ }
D. with(object) -> { /* code block */ }
Solution
Step 1: Recall the syntax of with
The correct syntax is with(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 A
Quick Check:
Correct with syntax uses parentheses and braces = A [OK]
Hint: Use parentheses for object, braces for block in with [OK]
Common Mistakes:
Omitting parentheses around the object
Using arrow notation incorrectly
Placing the block outside braces
3. What is the output of the following Kotlin code?
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)
}
medium
A. Alice is now 25 years old
B. Runtime error due to modifying age
C. Compilation error due to string interpolation
D. Alice is now 26 years old
Solution
Step 1: Analyze the with block behavior
The with function uses person as the context. Inside, age is 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 D
Quick Check:
Age incremented inside with = D [OK]
Hint: Remember last expression in with is the return value [OK]
4. Identify the error in this Kotlin code using with:
fun main() {
val list = listOf(1, 2, 3)
with(list) {
add(4)
println(this)
}
}
medium
A. Cannot call add on an immutable list
B. Missing parentheses in with call
C. Incorrect use of this inside with
D. Print statement syntax error
Solution
Step 1: Check the list type and mutability
The list is created with listOf, which returns an immutable list that does not support add.
Step 2: Understand the error cause
Calling add(4) on an immutable list causes a compile-time error because the method is not available.
Final Answer:
Cannot call add on an immutable list -> Option A
Quick Check:
Immutable list blocks add method = A [OK]
Hint: Use mutableListOf to add elements, not listOf [OK]
Common Mistakes:
Assuming with changes mutability
Thinking this is incorrect inside with
Ignoring immutability of listOf
5. Given a mutable map of student names to scores, how can you use with to increase all scores by 5 points and return the updated map?
Choose the correct Kotlin code snippet.
hard
A. with(students) { keys.forEach { it += 5 }; this }
B. with(students) { for (key in keys) this[key] = this[key]!! + 5; this }
C. with(students) { mapValues { it.value + 5 } }
D. with(students) { forEach { it.value += 5 }; this }
Solution
Step 1: Understand map mutability and with usage
The map is mutable, so we can update values by keys inside with. 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 modify it.value in forEach, but map entries are immutable in this context.
Final Answer:
with(students) { for (key in keys) this[key] = this[key]!! + 5; this } -> Option B
Quick Check:
Update map values by keys inside with = B [OK]
Hint: Use keys to update mutable map values inside with [OK]
Common Mistakes:
Trying to modify keys instead of values
Assuming mapValues mutates original map
Modifying map entries directly in forEach causes error
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.