0Pricing
Kotlin Academy · Lesson

Best Practices

Keep operators intuitive.

Keep Operators Intuitive

Overload an operator only when its meaning is obvious. + on vectors is clear; + meaning send-email is not.

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

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

Preserve Expected Semantics

Honor the usual algebra: a + b should be commutative-feeling for symmetric types and should not surprise readers.

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

fun main() {
    println(Money(100) + Money(50))
}

All lessons in this course

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