Bird
0
0

What will be the output of this Kotlin code?

medium📝 Predict Output Q4 of 15
Kotlin - Operators and Expressions
What will be the output of this Kotlin code?
data class Number(val value: Int) {
  operator fun plus(other: Number) = Number(value + other.value)
}

fun main() {
  val a = Number(5)
  val b = Number(3)
  val c = a + b
  println(c.value)
}
A8
B53
CError: operator not defined
D0
Step-by-Step Solution
Solution:
  1. Step 1: Understand operator plus function

    The plus operator adds the 'value' properties of two Number objects and returns a new Number.
  2. Step 2: Calculate the sum of values

    a.value is 5, b.value is 3, so c.value = 5 + 3 = 8.
  3. Final Answer:

    8 -> Option A
  4. Quick Check:

    Operator plus function output = 8 [OK]
Quick Trick: Operator functions return new objects with combined values [OK]
Common Mistakes:
MISTAKES
  • Concatenating values as strings
  • Expecting runtime error without operator
  • Assuming default plus behavior for custom class

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes