Operator overloading is one of Kotlin’s most beloved features.
It lets you give familiar syntax to custom types, and you’re probably already using it without even noticing it.
Take the Map interface, for example: the indexed access operator ([]) is used to read and write entries:
val m = mutableMapOf<Int, String>()
m[1] = "one" // m.put(1, "one")
val value = m[1] // m.get(1)
The same syntax works for arrays, lists, and any type that declares an operator fun get or operator fun set.
Did you know that you can overload the indexed access operator with multiple indices?
Continue reading →
Considering a move to Kotlin? Coming from a Java background?
In this short series of blog posts, I’ll take a look at familiar, straightforward Java concepts and demonstrate how you can approach them in Kotlin.
While many of these points have already been discussed in earlier posts by colleagues, my focus is simple: how you used to do it in Java, and how you do it in Kotlin.
Case 12:
In this post, we explore how to model a finite set of types in Java — the “old way” with enums or class hierarchies, the “new way” with Java SE 17+ sealed classes — and then see how Kotlin handles them elegantly with sealed classes.
Continue reading →
Considering a move to Kotlin? Coming from a Java background?
In this short series of blog posts, I’ll take a look at familiar, straightforward Java concepts and demonstrate how you can approach them in Kotlin.
While many of these points have already been discussed in earlier posts by colleagues, my focus is simple: how you used to do it in Java, and how you do it in Kotlin.
Case 11:
You want to construct an object.
With many parameters.
Some optional.
Readable.
Preferably without a constructor that looks like a password.
Continue reading →