Bird
0
0

You want to create a Kotlin class Vector that supports both addition (+) and multiplication (*) operators. How should you design these operators as functions to keep your code clean and flexible?

hard📝 Application Q15 of 15
Kotlin - Operators and Expressions
You want to create a Kotlin class Vector that supports both addition (+) and multiplication (*) operators. How should you design these operators as functions to keep your code clean and flexible?
ACreate separate classes for addition and multiplication
BUse global functions without 'operator' keyword
CDefine 'operator fun plus' and 'operator fun times' inside Vector class
DOverride '+' and '*' symbols directly without functions
Step-by-Step Solution
Solution:
  1. Step 1: Understand operator overloading in Kotlin

    Kotlin requires operator functions inside the class or as extensions with the 'operator' keyword.
  2. Step 2: Choose the clean design

    Defining 'operator fun plus' and 'operator fun times' inside Vector class keeps code organized and flexible.
  3. Final Answer:

    Define 'operator fun plus' and 'operator fun times' inside Vector class -> Option C
  4. Quick Check:

    Operator functions inside class = clean, flexible [OK]
Quick Trick: Put operator functions inside class with 'operator' keyword [OK]
Common Mistakes:
MISTAKES
  • Trying to override symbols directly
  • Omitting 'operator' keyword
  • Using global functions without operator keyword

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes