Bird
0
0

Given this Kotlin class:

hard📝 Application Q15 of 15
Kotlin - Operators and Expressions
Given this Kotlin class:
class Vector(val x: Int, val y: Int) {
    operator fun plus(other: Vector) = Vector(x + other.x, y + other.y)
    operator fun times(scalar: Int) = Vector(x * scalar, y * scalar)
}

What is the result of this expression?
val v1 = Vector(2, 3)
val v2 = Vector(1, 1)
val result = (v1 + v2) * 2
println("(${result.x}, ${result.y})")
A(3, 4)
B(4, 6)
C(6, 8)
DCompilation error due to operator precedence
Step-by-Step Solution
Solution:
  1. Step 1: Evaluate v1 + v2

    v1 is (2,3), v2 is (1,1). Adding gives Vector(3,4).
  2. Step 2: Multiply the result by 2

    Vector(3,4) times 2 gives Vector(6,8).
  3. Step 3: Print the result

    Printing prints (6, 8) as expected.
  4. Final Answer:

    (6, 8) -> Option C
  5. Quick Check:

    (v1 + v2) * 2 = (6, 8) [OK]
Quick Trick: Evaluate plus first, then times; operator overloading respects precedence [OK]
Common Mistakes:
MISTAKES
  • Multiplying v2 by 2 instead of the sum
  • Ignoring operator precedence
  • Expecting compilation error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes