Bird
Raised Fist0
Kotlinprogramming~10 mins

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

Choose your learning style10 modes available
Concept Flow - Run function behavior and use cases
Call run on object
↓
Execute lambda with 'this' as receiver
↓
Lambda body runs using object's context
↓
Return lambda result
↓
Use returned value or end
The run function executes a block of code with the object as its context and returns the block's result.
Execution Sample
Kotlin
val result = "Hello".run {
    println(this)
    length
}
Runs a block on the string "Hello", prints it, and returns its length.
Execution Table
StepActionEvaluationResult
1Call run on "Hello"run block starts with 'this' = "Hello"Lambda ready to execute
2Print thisPrints "Hello" to consoleOutput: Hello
3Evaluate length"Hello".length5
4Return lengthrun returns 5result = 5
5EndNo more codeExecution stops
💡 run block finished and returned length 5
Variable Tracker
VariableStartAfter run callAfter lambda executionFinal
thisN/A"Hello""Hello"N/A
resultN/AN/A55
Key Moments - 3 Insights
Why does 'this' inside run refer to the object?
Because run executes the lambda with the object as the receiver, so 'this' points to the object (see execution_table step 1).
What does run return?
It returns the last expression value inside the lambda block (see execution_table step 4 where it returns 5).
Can run be used to execute multiple statements on an object?
Yes, run allows multiple statements inside the lambda using the object's context (see execution_table steps 2 and 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'result' after the run block finishes?
Anull
B"Hello"
C5
Dlength of lambda
💡 Hint
Check execution_table row 4 where run returns 5 assigned to result.
At which step does the lambda print the string?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at execution_table row 2 where println(this) happens.
If we replaced 'length' with 'this.uppercase()', what would run return?
A"HELLO"
B5
CUnit
DError
💡 Hint
run returns the last expression value inside the lambda (see execution_table step 4).
Concept Snapshot
run function syntax:
object.run { /* lambda with 'this' as receiver */ }

Behavior:
- Executes lambda with object as 'this'
- Returns lambda's last expression

Use cases:
- Access object members concisely
- Execute multiple statements on object
- Return computed result from block
Full Transcript
The run function in Kotlin lets you run a block of code with an object as its context, meaning inside the block 'this' refers to the object. When you call run on an object, it executes the lambda you provide, and the last expression inside that lambda is returned as the result. For example, calling run on the string "Hello" and printing 'this' inside prints Hello, then returning length returns 5. Variables 'this' and 'result' change accordingly during execution. Beginners often wonder why 'this' refers to the object, what run returns, and if multiple statements can be used inside run. The answers are that run uses the object as receiver, returns the last lambda expression, and supports multiple statements. Visual quizzes help reinforce these points by asking about the result value, when printing happens, and what happens if the last expression changes. The quick snapshot summarizes syntax, behavior, and use cases for easy recall.

Practice

(1/5)
1. What does the Kotlin run function do when called without an object?
easy
A. Creates a new thread to run the block asynchronously
B. Delays the execution of the block until explicitly called
C. Executes the given block and returns the last expression's value
D. Throws an exception if the block contains no return statement

Solution

  1. Step 1: Understand run without receiver

    When run is called without an object, it simply executes the block of code inside it.
  2. Step 2: Identify the return value

    The function returns the value of the last expression inside the block.
  3. Final Answer:

    Executes the given block and returns the last expression's value -> Option C
  4. Quick Check:

    run without object returns last expression [OK]
Hint: run returns last expression value in its block [OK]
Common Mistakes:
  • Thinking run creates a new thread
  • Assuming run delays execution
  • Believing run throws error without explicit return
2. Which of the following is the correct syntax to use run with an object in Kotlin?
easy
A. val result = run.obj { property + 1 }
B. val result = obj.run { this.property + 1 }
C. val result = run { obj.property + 1 }
D. val result = obj.run() { property + 1 }

Solution

  1. Step 1: Identify correct run usage with receiver

    The run function is called as an extension on the object: obj.run { ... }.
  2. Step 2: Check syntax correctness

    val result = obj.run { this.property + 1 } correctly uses obj.run { this.property + 1 } without extra parentheses or misplaced dots.
  3. Final Answer:

    val result = obj.run { this.property + 1 } -> Option B
  4. Quick Check:

    run called as extension function on object [OK]
Hint: run is called as extension: obj.run { ... } [OK]
Common Mistakes:
  • Using dot after run like run.obj
  • Adding empty parentheses after run
  • Calling run without object but expecting receiver
3. What is the output of this Kotlin code?
val result = run {
    val x = 5
    val y = 10
    x + y
}
println(result)
medium
A. Compilation error
B. 510
C. null
D. 15

Solution

  1. Step 1: Execute the run block

    The block declares x = 5 and y = 10, then returns x + y which is 15.
  2. Step 2: Print the result

    The variable result holds 15, so println(result) outputs 15.
  3. Final Answer:

    15 -> Option D
  4. Quick Check:

    run returns last expression value 15 [OK]
Hint: run returns last expression value inside block [OK]
Common Mistakes:
  • Concatenating numbers as strings
  • Expecting null because no explicit return
  • Thinking run causes compilation error
4. Identify the error in this Kotlin code using run:
val text = "Hello"
val length = text.run {
    val len = length
}
println(length)
medium
A. The run block does not return a value, so length is assigned Unit
B. The variable len is not accessible outside run block
C. The property length is undefined for String
D. The run function cannot be called on a String

Solution

  1. Step 1: Analyze run block return

    The run block declares val len = length but does not return any expression explicitly, so it returns Unit.
  2. Step 2: Check assignment to length variable

    Variable length is assigned the result of run, which is Unit, not the integer length of the string.
  3. Final Answer:

    The run block does not return a value, so length is assigned Unit -> Option A
  4. Quick Check:

    run returns last expression; no explicit return means Unit [OK]
Hint: run returns last expression; no explicit return means Unit [OK]
Common Mistakes:
  • Assuming len is returned automatically
  • Confusing property length with variable
  • Thinking run cannot be called on String
5. Given a list of nullable integers val numbers = listOf(1, null, 3, null, 5), how can you use run to compute the sum of non-null values safely in Kotlin?
hard
A. val sum = numbers.run { filterNotNull().sum() }
B. val sum = run(numbers) { filterNotNull().sum() }
C. val sum = numbers.run { sum() }
D. val sum = run { filterNotNull().sum() }

Solution

  1. Step 1: Use run as extension on list

    Calling numbers.run { ... } lets you access list functions directly inside the block.
  2. Step 2: Filter non-null and sum

    Inside the block, filterNotNull() removes nulls, then sum() adds remaining numbers.
  3. Final Answer:

    val sum = numbers.run { filterNotNull().sum() } -> Option A
  4. Quick Check:

    run with receiver simplifies code, returns last expression [OK]
Hint: Use run as extension to chain calls on object [OK]
Common Mistakes:
  • Passing list as argument to run incorrectly
  • Calling sum() without filtering nulls
  • Using run without receiver and accessing list members directly
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