Bird
0
0

What will be printed when this Kotlin code runs?

medium📝 Predict Output Q5 of 15
Kotlin - Functions
What will be printed when this Kotlin code runs?
fun outer() {
    val prefix = "Hi"
    fun inner(name: String) {
        println("$prefix, $name")
    }
    inner("Alice")
}
outer()
AHi Alice
BHi, Alice
Cprefix, Alice
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Analyze variable access in inner function

    The inner function uses the outer variable prefix which is "Hi".
  2. Step 2: Check the print statement

    It prints "$prefix, $name" which becomes "Hi, Alice" when inner("Alice") is called.
  3. Final Answer:

    Hi, Alice -> Option B
  4. Quick Check:

    Local function accesses outer variable = "Hi, Alice" [OK]
Quick Trick: Local functions can use outer variables directly [OK]
Common Mistakes:
MISTAKES
  • Missing comma in output
  • Expecting variable name printed literally
  • Assuming compilation error due to string interpolation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes