liveBook · Manning

Custom operator

As explained in Kotlin in Action, 2E

A custom operator is a programmer-provided implementation of a predefined operator symbol.

A custom operator gives a predefined Kotlin symbol such as +, *, in, or [] a programmer-provided implementation for a type. Kotlin limits the available symbols, keeping expressions concise without allowing cryptic, undocumented punctuation. section 1.4.2 section 9.1.1

Adding points with +

data class Point(val x: Int, val y: Int) { operator fun plus(other: Point): Point { return Point(x + other.x, y + other.y) } } fun main() { println(Point(10, 20) + Point(30, 40)) // Point(x=40, y=60) } The operator modifier connects the expression p1 + p2 with a plus function call. The same convention can be written as an extension function, which is useful for external library types. section 9.1.1

Kotlin operator implementations follow fixed conventions:

  • Map symbols to named functions: *, /, %, +, and - correspond to times, div, mod, plus, and minus. section 9.1.1
  • Support different operand and return types; for example, Point * Double can return Point, while Char * Int can return String. section 9.1.1
  • Preserve standard precedence, so multiplication still binds more tightly than addition for user-defined types. section 9.1.1
  • Use infix functions when operand-centered syntax is useful but no predefined operator fits. 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 the complete Point.plus implementation and its runnable result. section 9.1.1

How Kotlin in Action, 2E covers it

How deep it goes
Explains member and extension implementations, mappings, precedence, type variation, infix alternatives, and Java calls.
Examples
Demonstrates Point addition and scaling, character repetition, bitwise expressions, and Flow-to-State conversion in Compose.
What it assumes
Assumes Kotlin functions and types, while introducing operator modifiers, extension functions, and infix alternatives through examples.
What you can do after
Build it from scratch for custom types using operator functions or extensions, and call Kotlin operators from Java as regular functions.
How it connects
Connects operator overloading with extension functions, infix functions, Java interoperability, Kotlin Flow, and Jetpack Compose.

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.