Bird
0
0

Find the error in this Kotlin operator function:

medium📝 Debug Q6 of 15
Kotlin - Operators and Expressions
Find the error in this Kotlin operator function:
class Vector(val x: Int, val y: Int) {
  fun minus(other: Vector) {
    return Vector(x - other.x, y - other.y)
  }
}
AOperator keyword is missing
BFunction must declare return type Vector
CCannot use minus operator for Vector class
DFunction parameters are incorrect
Step-by-Step Solution
Solution:
  1. Step 1: Check for the operator keyword

    The function definition lacks the 'operator' keyword, which is required to overload operators.
  2. Step 2: Role of the operator keyword

    Without 'operator', the function named 'minus' is just a regular method and won't be called by the '-' syntax.
  3. Final Answer:

    Operator keyword is missing -> Option A
  4. Quick Check:

    Operator keyword is required for overloading [OK]
Quick Trick: Always include 'operator' keyword before fun for operator functions [OK]
Common Mistakes:
MISTAKES
  • Omitting return type when returning new object
  • Forgetting operator keyword
  • Misnaming function parameters

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes