🚀 · Introduction

2 min read · Updated on by

Read on for an introduction to scope functions, what they are, why they can be confusing and how the official documentation is somewhat lacking in explaining them.

Extensions enable us to create many interesting utilities that give programming Kotlin an entirely new dimension compared to many other mainstream languages. One of the prime examples are the so-called scope functions.

Scope functions are a set of fairly simple extension functions, and are part of the Kotlin Standard Library. Indeed, they are so simple that at first glance, one has no idea why they exists in the first place, much less why they’re included as part of the standard library.

Like many other Kotlin features, their purpose is mainly to make code more concise, easier to read, and most importantly to communicate intent. As is often the case with such features, they only shine if used properly, and there is a lot of confusion around when and how to use them, as evidenced by the multitude of articles written about them. With great power comes great responsibility, and overuse can actually make matters worse.

The scope function are alsoapplyletrunwith, and we will also be mentioning takeIf and takeUnless.

It is important to emphasize that the intent with which these functions are used is very much open to interpretation, and you may come across very disparate opinions if you do your own research (which you absolutely should). The Primer presents its own point of view, and gives supporting arguments for why it thinks it is a reasonable one, but does so with the disclaimer that it is nothing more than that — a point of view.

While the documentation page does discuss when you should use a given scope function, and how it should be interpreted, I feel that it is somewhat lacking in certain ways. For one, the descriptions are often brief and non-illuminating, but more importantly, much of the information stated there is simply declared, without demonstrating why a certain style of usage should be preferred. The differences between the individual scope functions are often very nuanced, but this nuance is not always addressed explicitly in the documentation.

It could be argued that this is not what the documentation is for, however I think it is important to understand these things a little deeper. Therefore, the following articles will expand on, and clarify, what is written in the documentation, give examples, as well as give an explanation for why things should be interpreted in a particular manner, and compare the individual scope functions to tease out the differences in how they should be used.

As always, I would like to encourage you to make up your own mind, and find a style that you feel best expresses what you mean. In other words: you do you.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

The Kotlin Primer