Bird
0
0

What will be printed by this Kotlin code?

medium📝 Predict Output Q5 of 15
Kotlin - Functions
What will be printed by this Kotlin code?
infix fun String.repeat(times: Int) = buildString { repeat(times) { append(this@repeat) } }

fun main() {
    val result = "Hi" repeat 3
    println(result)
}
AHi repeat 3
BHiHiHi
CHi 3
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Understand the infix extension function

    The infix function repeat calls the standard String.repeat(times) method, repeating the string.
  2. Step 2: Evaluate the call "Hi" repeat 3

    This repeats "Hi" three times, resulting in "HiHiHi".
  3. Final Answer:

    HiHiHi -> Option B
  4. Quick Check:

    Infix extension repeats string = HiHiHi [OK]
Quick Trick: Infix extension functions can call existing methods cleanly [OK]
Common Mistakes:
MISTAKES
  • Expecting spaces between repeats
  • Confusing infix with string concatenation
  • Assuming syntax error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes