Operator Functions
Explore how to implement Kotlin operator functions to customize common symbols like plus, minus, times, and more for your own types. Understand operator notations including infix, prefix, and postfix to write clearer and more expressive Kotlin code.
We'll cover the following...
Operator functions allow you to define the meaning of well-known symbols such as + and - for your own types.
Introducing Operators #
Kotlin’s operators allow calling functions using certain symbols. For instance, the infix + operator actually calls a plus function so that a + b translates to a.plus(b) under the hood.
Many operators use infix notation and therefore can be seen as an extension of infix functions. Instead of a function name, operator functions instead use an operator symbol. However, there are also operators using prefix and postfix notation:
- Prefix:
+a,-a,!a - Infix:
a * b,a..b,a == b, … - Postfix:
a[i],a()
Kotlin has a predefined list of possible operators you can use (in contrast to languages like Scala or Haskell).
...Important Kotlin Operators #