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
