Scope Functions: Closing Remarks & Exercises
How scope functions solve readability problems, not coding problems, how their usage is not standardized, how to use them properly and a whole range of exercises to really get them down.
— — — — — — — — — — — — — — —
THE CURRENT VERSION OF THIS ARTICLE IS PUBLISHED HERE.
— — — — — — — — — — — — — — —

Tags: #FUNDAMENTAL CONCEPT #EXERCISE
This article is part of the Kotlin Primer, an opinionated guide to the Kotlin language, which is indented to help facilitate Kotlin adoption inside Java-centric organizations. It was originally written as an organizational learning resource for Etnetera a.s. and I would like to express my sincere gratitude for their support.
It is recommended to read the Introduction before moving on. Check out the Table of Contents for all articles.
I hope this excursion into some of the most important functions from the Kotlin standard library has opened a new door in the way you think about designing code. One of the things that makes Kotlin unique is that it contains features solely for the benefit of the future reader, and not actual functionality. They are not there to make solving some type of problem easier, but to better express ourselves and communicate with the person who will be reading our code. Nowhere is this more true than in the context of scope functions.
However, as was said before, the meaning associated to these functions does not seem to be standardized. I have shown you my point of view, and shown you why I think it’s a reasonable one, but this is by no means what you will always encounter in the real world, and you don’t have to go far to find usages that are different. Indeed, the lead designer of Kotlin wrote an article in which he used with in a situation where, according to what was just said, he should have used apply or run. That does not make it right or wrong, merely open to interpretation. This is why I encourage you to find a style that you feel is right, and be consistent about it.
At the same time, I would like to stress that it is very easy to overuse scope functions, and in fact, many people do, especially when they first start out using Kotlin. While this is to be expected, it is good to keep in mind that usually, the only good reason to use a scope function is to communicate intent and/or make things easier to read. It is almost never a good idea to use scope functions only for the purpose of making code shorter, although, naturally, there are exceptions to every rule. As always, I encourage you to think critically about what you write, as opposed to binding yourself to a set of rules dogmatically.
I also strongly recommend watching the excellent talk Putting down the golden hammer, which discussed the abuse of Kotlin features (not only scope functions) in depth.







