Bird
0
0

What will be the output of this Kotlin code?

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

fun main() {
    val p1 = Point(1, 2)
    val p2 = Point(3, 4)
    val p3 = p1 + p2
    println(p3)
}
APoint(4, 6)
BPoint(x=4, y=6)
CError: Operator '+' not defined
DPoint(x=1, y=2) + Point(x=3, y=4)
Step-by-Step Solution
Solution:
  1. Step 1: Understand operator plus function

    The plus operator adds x and y values of two Point objects and returns a new Point.
  2. Step 2: Calculate the result

    p1 + p2 = Point(1+3, 2+4) = Point(4, 6). Printing a data class shows property names.
  3. Final Answer:

    Point(x=4, y=6) -> Option B
  4. Quick Check:

    p1 + p2 = Point(x=4, y=6) [OK]
Quick Trick: Data class print shows property names [OK]
Common Mistakes:
MISTAKES
  • Expecting Point(4, 6) without property names
  • Thinking '+' is undefined
  • Printing the expression instead of result

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes