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 value: Int) {
    operator fun inc(): Counter {
        value += 1
        return this
    }
}

fun main() {
    var c = Counter(5)
    println(c++)
    println(c.value)
}
ACounter(value=5) 6
B5 6
CCounter(value=6) 6
DCounter@hashcode 6
Step-by-Step Solution
Solution:
  1. Step 1: Understand 'inc' operator and println behavior

    The 'inc' operator increments value by 1 and returns the same object. Printing the object without toString() shows default hashcode.
  2. Step 2: Analyze output of println(c++) and println(c.value)

    First println prints the object reference (like Counter@hashcode), second prints updated value 6.
  3. Final Answer:

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

    Increment operator prints object reference by default [OK]
Quick Trick: Without toString(), objects print as class@hashcode [OK]
Common Mistakes:
MISTAKES
  • Expecting pretty print without overriding toString()
  • Confusing postfix increment with prefix
  • Assuming println prints value automatically

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes