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
Critical Insight
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.