Bird
0
0

What will be the output of the following Kotlin code?

medium📝 Predict Output Q13 of 15
Kotlin - Functions
What will be the output of the following Kotlin code?
fun greet() {
    val prefix = "Hello"
    fun sayName(name: String) {
        println("$prefix, $name!")
    }
    sayName("Alice")
}
fun main() {
    greet()
}
AHello, Alice!
BHello Alice!
CError: prefix not accessible
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Understand variable scope in local functions

    The local function 'sayName' can access 'prefix' from the outer function 'greet'.
  2. Step 2: Trace the output of sayName("Alice")

    It prints "Hello, Alice!" exactly as formatted with the comma and exclamation mark.
  3. Final Answer:

    Hello, Alice! -> Option A
  4. Quick Check:

    Local function accesses outer variable = Hello, Alice! [OK]
Quick Trick: Local functions can use outer variables directly [OK]
Common Mistakes:
MISTAKES
  • Assuming outer variables are inaccessible
  • Missing punctuation in output
  • Thinking code produces error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes