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 Vector(val x: Int, val y: Int) {
    operator fun plus(other: Vector) = Vector(x + other.x, y + other.y)
}

fun main() {
    val v1 = Vector(1, 2)
    val v2 = Vector(3, 4)
    val v3 = v1 + v2
    println(v3)
}
AVector(x=4, y=6)
BVector(4, 6)
CError: Operator '+' not defined
DVector(x=1, y=2) + Vector(x=3, y=4)
Step-by-Step Solution
Solution:
  1. Step 1: Understand operator plus function

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

    v1 has (1,2), v2 has (3,4), so the result is Vector(1+3, 2+4) = Vector(4,6). The data class prints as Vector(x=4, y=6).
  3. Final Answer:

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

    Operator plus output = Vector(x=4, y=6) [OK]
Quick Trick: Data classes print properties with names by default [OK]
Common Mistakes:
MISTAKES
  • Expecting tuple-like print without property names
  • Assuming operator '+' 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