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
Kotlin conventions let you replace verbose function calls with intuitive operators by adding a single operator keyword to extension functions.
About This Article
Kotlin developers used to write verbose imperative code like `result = Number(1).plus(Number(2))` for basic arithmetic. These function calls made code harder to read and less expressive, which was especially problematic in mobile banking applications.
Gopinath Langote's article explains how to use Kotlin's `operator` keyword with extension functions to map arithmetic operations to symbols. This lets you write `ten + seven` instead of `ten.plus(seven)`, with compile-time checks on parameter and return types.
N26's engineering team found that six comparison operators (`>`, `<`, `==`, `!=`, `>=`, `<=`) can be implemented through a single `compareTo` convention function. This cuts down on boilerplate and makes their mobile banking platform easier to maintain.