Overloading Operators
Explore how to overload operators in Kotlin to write fluent and expressive code. Understand the benefits and risks, learn the mapping of operators to special functions, and discover practical guidelines to implement operator overloading correctly for user-defined classes.
We'll cover the following...
Need for operator overloading
Traditionally we use operators on numeric types to create expressions, for example, or . Operator overloading is a feature where the language extends the capability to use operators on user-defined data types.
Compare the two lines in the following code snippet:
bigInteger1.multiply(bigInteger2)
bigInteger1 * bigInteger2
The first line uses the multiply method from the JDK. The second line uses the * operator on the instances of BigInteger; that operator comes from the Kotlin standard library. The second line takes less effort—both to write and to read—than the first line, even though they both accomplish the same thing. The operator * makes the code look more natural, fluent, less code-like than the use of the multiply() method. Java doesn’t permit us to overload operators on user-defined datatypes, but Kotlin does. That leads to greater fluency, less clutter, and makes it a joy to program in Kotlin.
Benefits of operator overloading
In addition to using operators like +, -, and * on numeric types, languages that support ...