Bird
Raised Fist0
Kotlinprogramming~10 mins

With function behavior and use cases in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - With function behavior and use cases
Call with(obj) { block }
↓
Inside block: 'this' refers to obj
↓
Execute block using obj's members
↓
Return block result
↓
End
The with function takes an object and a block of code. Inside the block, 'this' means the object, so you can call its methods or properties directly. It returns the block's result.
Execution Sample
Kotlin
val person = Person("Anna", 25)
val result = with(person) {
    "Name: $name, Age: $age"
}
println(result)
Creates a Person object and uses with to access its properties directly, returning a formatted string.
Execution Table
StepActionEvaluationResult
1Create person objectPerson(name="Anna", age=25)person = Person("Anna", 25)
2Call with(person) { ... }Enter block with 'this' = personContext set to person
3Evaluate block: "Name: $name, Age: $age"Substitute name and age from person"Name: Anna, Age: 25"
4Return block resultBlock returns stringresult = "Name: Anna, Age: 25"
5Print resultOutput to consoleName: Anna, Age: 25
💡 Block executed fully, with returned string assigned to result and printed.
Variable Tracker
VariableStartAfter Step 1After Step 4Final
personnullPerson(name="Anna", age=25)Person(name="Anna", age=25)Person(name="Anna", age=25)
resultnullnull"Name: Anna, Age: 25""Name: Anna, Age: 25"
Key Moments - 3 Insights
Why can we access 'name' and 'age' without prefix inside the with block?
Inside the with block, 'this' refers to the object passed (person), so its properties can be accessed directly without prefix, as shown in step 3 of the execution_table.
What does the with function return?
The with function returns the last expression inside its block. Here, it returns the formatted string, as shown in step 4 of the execution_table.
Can we use with to modify the object properties?
Yes, inside the with block you can call methods or set properties on the object because 'this' refers to it. This is implied by the context set in step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'result' after step 4?
Anull
BPerson object
C"Name: Anna, Age: 25"
D"Anna, 25"
💡 Hint
Check the 'Result' column in row for step 4 in execution_table.
At which step does the with function set 'this' to the person object?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column describing entering the block with 'this' set.
If we changed the block to modify 'age' by adding 1, what would happen to 'person.age' after with?
AIt stays the same
BIt increases by 1
CIt becomes null
DIt throws an error
💡 Hint
Recall that inside with, 'this' is the object, so modifying properties affects the original object.
Concept Snapshot
with(obj) { block } runs block with 'this' as obj.
Inside block, access obj's members directly.
Returns last expression of block.
Useful for grouping calls on one object.
Simplifies code by avoiding repeated obj references.
Full Transcript
The with function in Kotlin takes an object and a block of code. When you call with(obj) { block }, inside the block 'this' means the object, so you can use its properties and methods directly without repeating the object name. The function runs the block and returns the last expression's value. For example, if you have a person object with name and age, you can write with(person) { "Name: $name, Age: $age" } to get a formatted string. This makes code cleaner and easier to read. You can also modify the object inside the block because 'this' refers to it. The execution steps show creating the object, entering the block with 'this' set, evaluating the block, returning the result, and printing it. Variables person and result change as expected. Common confusions include why you can access properties without prefix, what with returns, and if you can modify the object inside. The quiz checks understanding of these points.

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

  1. 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.
  2. Step 2: Compare with other options

    Options A, B, and D describe unrelated Kotlin features like class definition, threading, and exception handling.
  3. Final Answer:

    To execute multiple operations on the same object without repeating its name -> Option C
  4. 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

  1. 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.
  2. Step 2: Identify incorrect syntax

    Options B, C, and D misuse arrow notation or omit parentheses, which are syntax errors.
  3. Final Answer:

    with(object) { /* code block */ } -> Option A
  4. 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

  1. 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.
  2. 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".
  3. Final Answer:

    Alice is now 26 years old -> Option D
  4. Quick Check:

    Age incremented inside with = D [OK]
Hint: Remember last expression in with is the return value [OK]
Common Mistakes:
  • Forgetting that age is incremented inside with
  • Thinking string interpolation causes error
  • Assuming modifying properties causes runtime error
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

  1. Step 1: Check the list type and mutability

    The list is created with listOf, which returns an immutable list that does not support add.
  2. Step 2: Understand the error cause

    Calling add(4) on an immutable list causes a compile-time error because the method is not available.
  3. Final Answer:

    Cannot call add on an immutable list -> Option A
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    with(students) { for (key in keys) this[key] = this[key]!! + 5; this } -> Option B
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard