Mastering Kotlin Conventions: Get, Set, and Range Operations
Article Summary
Gopinath Langote from N26 shows how Kotlin's operator overloading can transform verbose getter/setter code into elegant, readable syntax. Instead of date.getMonth() or date.setMonth(6), what if you could just write date[1] = 6?
This is Part II of a series on Kotlin conventions, focusing on four powerful operators: get, set, rangeTo, and contains. Using a Date class as a practical example, the article demonstrates how operator functions can make custom classes feel as intuitive as built-in language types.
Key Takeaways
- Implement get operator to access elements by index: date[0] returns day
- Use set convention for assignment syntax: date[1] = 6 sets the month
- Create ranges with rangeTo: date(1,1,2018)..date(31,12,2018) works naturally
- Check membership with contains: date(13,3,2018) in month(3,2018) returns boolean
- All operators work as member or extension functions on any class
Kotlin's operator conventions let you write custom classes that behave like native language types, replacing verbose method calls with intuitive bracket notation and range operators.
About This Article
Kotlin developers writing custom classes end up with verbose code. They have to use method calls like getMonth() and setMonth() instead of the simpler bracket notation that feels more natural.
Gopinath Langote shows how to use operator functions with the operator modifier. The get, set, rangeTo, and contains functions map to specific symbols, so a Date class can support bracket syntax like date[0] and range operations like date(1,1,2018)..date(31,12,2018).
Kotlin's operator overloading lets developers make custom classes work like built-in types. This cuts down on verbose getter and setter calls, making code shorter and easier to read while matching how the language itself works.