0Pricing
Kotlin Academy · Lesson

Operator Functions

Overload plus, minus, etc.

What Is Operator Overloading?

Operator overloading lets your types respond to symbols like + or -. You define a function with the operator modifier and a special name.

data class Point(val x: Int, val y: Int) {
    operator fun plus(o: Point) = Point(x + o.x, y + o.y)
}

fun main() {
    println(Point(1, 2) + Point(3, 4))
}

The operator Keyword

The operator modifier tells the compiler this function backs an operator. Without it, calling a + b would not work.

data class Money(val amount: Int) {
    operator fun plus(o: Money) = Money(amount + o.amount)
}

fun main() {
    println(Money(5) + Money(3))
}

All lessons in this course

  1. Operator Functions
  2. Comparison Operators
  3. Index and Invoke
  4. Best Practices
← Back to Kotlin Academy