N26 Gopinath Langote Dec 17, 2018

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

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.

The article reveals why rangeTo automatically works on any Comparable class, and how the standard library makes this magic happen behind the scenes.

About This Article

Problem

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.

Solution

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).

Impact

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.