Bird
0
0

How can you modify this Kotlin function to count how many times a local function is called?

hard📝 Application Q9 of 15
Kotlin - Functions
How can you modify this Kotlin function to count how many times a local function is called?
fun counter() {
    var count = 0
    fun increment() {
        count++
    }
    increment()
    increment()
    println(count)
}
ADeclare count as val instead of var.
BMove count variable inside increment() function.
CNo modification needed; it prints 2 correctly.
DCall increment() only once.
Step-by-Step Solution
Solution:
  1. Step 1: Understand variable scope and increments

    count is declared outside increment() and increment() increases count by 1 each call.
  2. Step 2: Check calls and print

    increment() is called twice, so count becomes 2, which is printed correctly.
  3. Final Answer:

    No modification needed; it prints 2 correctly. -> Option C
  4. Quick Check:

    Local function modifies outer variable correctly [OK]
Quick Trick: Outer variables can be changed by local functions [OK]
Common Mistakes:
MISTAKES
  • Moving count inside increment resets it each call
  • Using val prevents increment
  • Reducing calls changes count incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes