liveBook · Manning

Operator overloading

As explained in Kotlin in Action, 2E

Operator overloading is a language feature that assigns custom implementations to predefined operator symbols.

Operator overloading lets Kotlin map familiar operator syntax to specially named functions. Define `plus` and write `a + b`; define `get`, `set`, or `contains` to support collection-like `[]` and `in` syntax. This is part of Kotlin’s convention system: language constructs call functions you provide rather than requiring a particular interface. The approach is especially useful for adapting existing Java classes through extension functions, without changing their source. section 9.0 section 9.6

Only a fixed set of predefined operators is available. Kotlin does not permit inventing new punctuation operators, preserving recognizable syntax and making code easier to read and find. When a named operation between two operands needs custom wording rather than a standard symbol, an infix function is an alternative. section 9.1.1 section 1.4.2

Adding points with +

A `Point` can define `operator fun plus(other: Point): Point`, returning a point whose coordinates are summed. After that declaration, `p1 + p2` is translated to a call to `p1.plus(p2)`. The `operator` modifier is required, making the convention intentional rather than accidental. The same implementation may be a member function or an extension function; extensions are useful when the target type comes from an external library. section 9.1.1

Listing 9.1 Defining the plus operator
data class Point(val x: Int, val y: Int) {
    operator fun plus(other: Point): Point {     #1
        return Point(x + other.x, y + other.y)   #2
    }
}
 
fun main() {
    val p1 = Point(10, 20)
    val p2 = Point(30, 40)
    println(p1 + p2)                             #3
    // Point(x=40, y=60)
}

Inspect a complete `Point.plus` declaration and the resulting `p1 + p2` call. The annotations distinguish the operator declaration, coordinate calculation, and use-site syntax. section 9.1.1

Arithmetic operator conventions follow a few practical rules:

  • Use the corresponding predefined function name, such as `times`, `div`, `mod`, `plus`, or `minus`, for binary arithmetic operators. section 9.1.1
  • Keep normal operator precedence: in `a + b * c`, multiplication runs before addition even when the operands are custom types. section 9.1.1
  • Accept operand and return types appropriate to the operation. A point can be multiplied by a `Double`, and a `Char` multiplied by an `Int` can return a `String`. section 9.1.1
  • Declare unary conventions with no arguments. For example, `unaryMinus` enables `-p`; `inc` and `dec` enable increment and decrement behavior. section 9.1.3

Increment and decrement retain the familiar distinction between prefix and postfix forms. With an `inc` implementation for `BigDecimal`, postfix `bd++` yields the current value before increasing it, while prefix `++bd` increases first. Kotlin supplies those prefix/postfix semantics automatically once the convention function is defined. section 9.1.3

Operator conventions extend beyond arithmetic. Equality and ordering operators map to `equals` and `compareTo`; `get`, `set`, and `contains` support indexed access and membership; ranges, iteration, destructuring, and delegated properties also use conventions. These mechanisms let custom types participate in ordinary Kotlin syntax while retaining explicit function implementations. section 9.6

How Kotlin in Action, 2E covers it

How deep it goes
Works through `operator` declarations, function mappings, precedence, operand types, extensions, and unary increment semantics; defers broader convention details.
Examples
Demonstrates Point addition, scaling, negation, Char repetition, and BigDecimal increment with prefix and postfix forms.
What it assumes
Assumes basic Kotlin function and class syntax while introducing operator declarations through compact examples.
What you can do after
Apply it via Kotlin `operator` functions to make supported predefined syntax work for custom or external types.
How it connects
Connects extension functions, infix functions, comparison operators, collections, ranges, destructuring declarations, and delegated properties.

Also explained in

Compare how 2 books explain operator overloading →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.