Bird
Raised Fist0
Kotlinprogramming~10 mins

Testing scope functions and lambdas in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Testing scope functions and lambdas
Define variable
↓
Call scope function
↓
Lambda executes with variable
↓
Modify or use variable inside lambda
↓
Return from scope function
↓
Use returned value or original variable
This flow shows how a variable is passed into a Kotlin scope function, modified or used inside a lambda, and then the result is returned or the original variable is used.
Execution Sample
Kotlin
val result = "hello".let {
  val upper = it.uppercase()
  upper + "!"
}
println(result)
This code uses the 'let' scope function to convert a string to uppercase and add an exclamation mark, then prints the result.
Execution Table
StepActionLambda Parameter (it)Intermediate ValueResult
1Call let on "hello""hello"
2Inside lambda: uppercase it"hello"HELLO
3Inside lambda: add '!'"hello"HELLO!
4Return from lambda"hello"HELLO!HELLO!
5Print resultHELLO!
💡 Lambda finishes and let returns the last expression value, which is printed.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
it"hello""hello""hello""hello"
upperN/A"HELLO""HELLO""HELLO"
resultN/AN/AN/A"HELLO!"
Key Moments - 3 Insights
Why does 'it' remain "hello" inside the lambda even after uppercase?
'it' is a read-only parameter representing the original string; uppercase() returns a new string without changing 'it' (see execution_table step 2).
What value does the 'let' function return?
'let' returns the last expression inside its lambda, here the string "HELLO!" (see execution_table step 4).
Why can we chain operations inside the lambda?
Because the lambda can contain multiple statements and the last one is returned, allowing transformations before returning (see execution_table steps 2 and 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'upper' after step 2?
A"hello"
B"HELLO"
C"HELLO!"
DN/A
💡 Hint
Check the 'Intermediate Value' column at step 2 in the execution_table.
At which step does the 'let' function return its final value?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look for the step labeled 'Return from lambda' in the execution_table.
If we changed the lambda to return just 'upper' without adding '!', what would 'result' be?
A"HELLO"
B"hello"
C"HELLO!"
Dnull
💡 Hint
Refer to the variable_tracker's final value for 'result' and imagine removing the '+ "!"' step.
Concept Snapshot
Kotlin scope functions like 'let' take a lambda with the object as 'it'.
Inside the lambda, you can transform or use 'it'.
The last expression in the lambda is returned.
Use scope functions to write concise, readable code with temporary variable scope.
Full Transcript
This example shows how Kotlin's 'let' scope function works. We start with a string "hello" and call 'let' on it. Inside the lambda, 'it' refers to the original string. We convert 'it' to uppercase and store it in 'upper'. Then we add an exclamation mark to 'upper'. The last expression "HELLO!" is returned from the lambda and assigned to 'result'. Finally, we print 'result', which outputs "HELLO!". The variable 'it' remains unchanged because strings are immutable. The key is that 'let' returns the last expression inside its lambda, allowing us to chain transformations cleanly.

Practice

(1/5)
1. Which Kotlin scope function returns the object it was called on after executing the given lambda?
easy
A. run
B. also
C. let
D. apply

Solution

  1. Step 1: Understand scope function behavior

    The also function executes the lambda with the object as it and returns the original object.
  2. Step 2: Compare with other functions

    let returns the lambda result, run returns lambda result, apply returns the object but uses this inside lambda.
  3. Final Answer:

    also -> Option B
  4. Quick Check:

    Returns original object after lambda = also [OK]
Hint: Remember: also returns object, let returns lambda result [OK]
Common Mistakes:
  • Confusing 'also' with 'let' return values
  • Mixing 'apply' and 'also' usage
  • Assuming 'run' returns the object
2. Which of the following is the correct syntax to use the let scope function on a nullable variable name?
easy
A. name?.let { println(it) }
B. name.let { println(it) }
C. let(name) { println(it) }
D. name?.let println(it)

Solution

  1. Step 1: Check nullable safe call usage

    To safely call let on a nullable variable, use the safe call operator ?..
  2. Step 2: Validate lambda syntax

    The lambda must be enclosed in braces {} and use it as the implicit parameter.
  3. Final Answer:

    name?.let { println(it) } -> Option A
  4. Quick Check:

    Safe call with lambda braces = name?.let { println(it) } [OK]
Hint: Use ?.let { } for nullable variables to avoid errors [OK]
Common Mistakes:
  • Omitting safe call operator on nullable
  • Incorrect lambda syntax without braces
  • Trying to call let as a standalone function
3. What is the output of this Kotlin code?
val result = "hello".run {
    println(this.uppercase())
    this.length
}
println(result)
medium
A. 5 HELLO
B. hello 5
C. HELLO hello
D. HELLO 5

Solution

  1. Step 1: Understand run behavior

    The run function executes the lambda with this as the receiver and returns the lambda's last expression.
  2. Step 2: Trace the code execution

    Inside lambda, println(this.uppercase()) prints "HELLO". Then this.length returns 5, assigned to result. Finally, println(result) prints 5.
  3. Final Answer:

    HELLO 5 -> Option D
  4. Quick Check:

    run prints uppercase then returns length = HELLO and 5 [OK]
Hint: run returns last lambda value; println outputs immediately [OK]
Common Mistakes:
  • Assuming run returns the printed string
  • Confusing this with it inside lambda
  • Mixing order of printed lines
4. Identify the error in this Kotlin code snippet:
val numbers = listOf(1, 2, 3)
numbers.also {
    it.add(4)
}
println(numbers)
medium
A. Missing lambda parameter name
B. also does not return the list
C. Cannot call add on immutable list
D. Syntax error in lambda

Solution

  1. Step 1: Check list mutability

    listOf creates an immutable list; calling add is not allowed.
  2. Step 2: Understand scope function effect

    also runs the lambda but does not change immutability; trying to add causes a runtime error.
  3. Final Answer:

    Cannot call add on immutable list -> Option C
  4. Quick Check:

    Immutable list blocks add() method = Cannot call add on immutable list [OK]
Hint: listOf creates immutable list; use mutableListOf to add [OK]
Common Mistakes:
  • Assuming also changes list mutability
  • Ignoring immutable list restrictions
  • Thinking lambda syntax is wrong
5. Given a list of nullable integers val nums = listOf(1, null, 3, null, 5), which code snippet correctly uses scope functions and lambdas to create a list of doubled non-null values?
hard
A. nums.filterNotNull().map { it * 2 }
B. nums.map { it * 2 }.filterNotNull()
C. nums.also { it.map { it * 2 } }
D. nums.run { map { it!! * 2 } }

Solution

  1. Step 1: Remove nulls before mapping

    Use filterNotNull() to exclude null values safely.
  2. Step 2: Map remaining values to double

    Apply map { it * 2 } on non-null list to double each integer.
  3. Final Answer:

    nums.filterNotNull().map { it * 2 } -> Option A
  4. Quick Check:

    Filter nulls then map doubling = nums.filterNotNull().map { it * 2 } [OK]
Hint: Filter nulls first, then map to avoid null errors [OK]
Common Mistakes:
  • Mapping before filtering nulls causes null results
  • Using unsafe !! operator risking exceptions
  • Misusing also or run without returning correct list
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