This Week I Learned: Kotlin has inline operators like I remember from C++ [2022–05–20]
To paraphrase wise old Chris from when I was a young developer, the wonderful thing about C++ allowing you to make your own operator schemes is that you can make something that beautifully suits you and your use case, and the worst thing is that everyone else does it too so then you have to deal with all of their crazy, nonsencial dumpster fires.
C++ would allow you to define inline operators using any of the predefined set of symbols (+
, -
, *
, %
and many others) without any real restrictions or even guidance, so then you’d be reading someone else’s code that they’d been solo-yolo-ing for too long and you’d come across shenanigans like multiplying an array of files by a string and then adding the result to a database iterator. Or, dividing a user by a date. What does that even mean? That adds time to understanding the code. In retrospect, everything in C++ was a footgun unless you were explicitly very careful.
It seems that Kotlin has brought these shenanigans into the 2020s. At least it forces you to read and type names that will give you some cognitive dissonance if you make the operator do something that doesn’t align with the words on your screen. E.g. if you’re making a +
operator you have to call the function plus()
.
It’s still potentially a footgun but possibly less so. These days there’s probably also a higher premium put on readable code.
data class Person(private val name: String)
data class People(private val people: List<Person>)inline operator fun Person.plus(somebodyElse: Person) = listOf(this, somebodyElse)fun printPeople() {
println(Person("me") + Person("you"))
}
You could actually write code to do what’s in the photo at the top.