Bird
0
0

How do you correctly define a Kotlin operator function to overload the multiplication (*) operator for a class?

easy📝 Syntax Q3 of 15
Kotlin - Operators and Expressions
How do you correctly define a Kotlin operator function to overload the multiplication (*) operator for a class?
Afun times operator(other: ClassName): ClassName
Bfun operator times(other: ClassName): ClassName
Coperator fun * (other: ClassName): ClassName
Doperator fun times(other: ClassName): ClassName
Step-by-Step Solution
Solution:
  1. Step 1: Use the 'operator' keyword before the function

    This keyword marks the function as an operator overload.
  2. Step 2: Define the function name as 'times' for the '*' operator

    Kotlin uses specific function names to map operators.
  3. Step 3: Specify the parameter and return type correctly

    The function should take the other operand and return the result.
  4. Final Answer:

    operator fun times(other: ClassName): ClassName -> Option D
  5. Quick Check:

    Keyword 'operator' + function name 'times' + correct syntax [OK]
Quick Trick: Use 'operator' keyword before function named after operator [OK]
Common Mistakes:
MISTAKES
  • Placing 'operator' after 'fun'
  • Using symbol '*' instead of function name 'times'
  • Omitting the 'operator' keyword

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes