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
