Mastering Kotlin Conventions: Operators and Arithmetic Operations
Article Summary
Gopinath Langote from N26 shows how Kotlin's operator overloading turns verbose code like Number(1).plus(Number(2)) into elegant Number(1) + Number(2). This isn't just syntactic sugar—it's a fundamental shift in how we write expressive Android code.
This practical guide from N26's engineering team breaks down Kotlin's operator conventions using a real-world Money class example. The article demonstrates how the operator keyword transforms standard functions into intuitive mathematical operators, making code more readable and maintainable.
Key Takeaways
- Operator keyword enables plus, minus, times, div to work as +, -, *, / symbols
- CompareTo convention replaces six separate comparison functions with standard operators
- Inc and dec operators allow ++ and -- syntax for custom types
- Each operator has compile-time restrictions on parameters and return types
Critical Insight
Kotlin conventions let you replace verbose function calls with intuitive operators by adding a single operator keyword to extension functions.