Bird
0
0

Find the error in this Kotlin operator overloading code:

medium📝 Debug Q7 of 15
Kotlin - Operators and Expressions
Find the error in this Kotlin operator overloading code:
data class Point(val x: Int, val y: Int) {
    operator fun times(factor: Int): Point {
        return Point(x * factor, y * factor)
    }
}

fun main() {
    val p = Point(2, 3)
    println(p * 2.0)
}
AMissing 'operator' keyword in times function
Btimes function must return Int, not Point
CCannot multiply Point by Double, only Int is supported
DData classes cannot overload operators
Step-by-Step Solution
Solution:
  1. Step 1: Check parameter type of times operator

    The times function accepts an Int parameter, but the code tries to multiply by 2.0 (Double).
  2. Step 2: Identify type mismatch error

    Multiplying by Double is not supported by this operator overload, causing a compile error.
  3. Final Answer:

    Cannot multiply Point by Double, only Int is supported -> Option C
  4. Quick Check:

    Operator parameter types must match usage [OK]
Quick Trick: Operator parameter types must match the operand types [OK]
Common Mistakes:
MISTAKES
  • Passing Double when function expects Int
  • Forgetting to add 'operator' keyword
  • Assuming data classes can't overload operators

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes