liveBook · Manning

Operator function

As explained in Kotlin in Action, 2E

An operator function is a Kotlin function marked with the operator modifier whose name and parameters implement a predefined operator convention.

An operator function is a Kotlin function marked with operator to implement a predefined operator convention. It lets an expression such as p1 + p2 call the corresponding plus function explicitly and intentionally. section 9.1.1

Adding points

data class Point(val x: Int, val y: Int) { operator fun plus(other: Point): Point = Point(x + other.x, y + other.y) } println(Point(10, 20) + Point(30, 40)) // Point(x=40, y=60) The function can be a member or an extension. The operator modifier prevents an ordinary function with a matching name from being used accidentally.

Use the predefined function name associated with each overloadable binary arithmetic operator:

  • Custom operators retain the standard numeric precedence; use infix functions when operand syntax is needed without a predefined operator. section 9.1.1

How Kotlin in Action, 2E covers it

How deep it goes
Explains declarations, member and extension forms, operand and return types, naming, precedence, and the boundary of predefined operators.
Examples
Demonstrates Point addition, Point scaling by Double, and Char repetition returning String.
What it assumes
Assumes basic Kotlin functions, classes, extensions, and expressions while clarifying operator conventions from concrete examples.
What you can do after
Build it from scratch by defining a permitted operator function and invoking it through familiar Kotlin syntax.
How it connects
Connects operator overloading with extension functions, infix functions, and operator precedence.

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.