Bird
0
0

What will be the output of this Kotlin code?

medium📝 Predict Output Q5 of 15
Kotlin - Operators and Expressions
What will be the output of this Kotlin code?
class Counter(var count: Int) {
  operator fun inc(): Counter {
    count++
    return this
  }
}

fun main() {
  var c = Counter(10)
  println(c++)
  println(c.count)
}
AError: inc operator must return new object
B10 and 11
C11 and 11
DCounter@hashcode and 11
Step-by-Step Solution
Solution:
  1. Step 1: Understand post-increment behavior

    c++ prints the object before increment, so it prints the object reference (like Counter@hashcode).
  2. Step 2: Check count after increment

    After c++, count is incremented to 11, so c.count prints 11.
  3. Final Answer:

    Counter@hashcode and 11 -> Option D
  4. Quick Check:

    Post-increment prints object then increments count [OK]
Quick Trick: Post-increment returns old value, then increments [OK]
Common Mistakes:
MISTAKES
  • Expecting count before increment on second print
  • Thinking inc must return new object always
  • Confusing pre-increment and post-increment

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes