Overloading Operators

Traditionally we use operators on numeric types to create expressions, for example, 2 + 3 or 4.2 * 7.1. 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 ...

Get Programming Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.