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(x=4, y=6)
Bp1 + p2
CCompilation error
DPoint(4, 6)
Step-by-Step Solution
Solution:
  1. Step 1: Understand operator plus function

    The plus operator adds the x and y values of two Point objects and returns a new Point with summed coordinates.
  2. Step 2: Calculate the result of p1 + p2

    p1 has (1, 2), p2 has (3, 4). Adding gives (4, 6). Printing p3 calls data class's toString(), which outputs 'Point(x=4, y=6)'.
  3. Final Answer:

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

    p1 + p2 = Point(x=4, y=6) [OK]
Quick Trick: Data class toString shows property names; sum coordinates [OK]
Common Mistakes:
MISTAKES
  • Expecting just coordinates without property names
  • Thinking '+' prints expression instead of result
  • Assuming compilation error without operator keyword

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes