The Concept of Operator Overloading
Somewhere, the programming language needs to know that /
means division, and it needs to actually implement the division functionality.
Worse, the division logic may vary somewhat by data type. Dividing two integers might be handled somewhat differently than would dividing two floating-point numbers.
Some languages simply “bake in” their support for operators and their corresponding operations. Java, for example, considers operators and what they do to be part of the core language.
Other languages — such as Kotlin — support operator overloading. Simply put:
- The language defines a mapping between an operator and a function name (e.g.,
/
mapping to adivide()
function) - The language’s standard library offers implementations of the function for expected data types (e.g.,
divide()
onNumber
) - The language allows developers to implement the same-named function on other classes and gain operator support for those classes (e.g.,
divide(Int)
onString
to support splitting a string into a specified number of pieces)
Some languages — such as Swift — take the next step and allow developers to define brand-new operators (e.g., ***
), which then get treated the same as the standard operators. Kotlin does not go to that length, though.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.