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
- Operator Functions
- Comparison Operators
- Index and Invoke
- Best Practices