
Member-only story
Kotlin’s five powerful scope functions you should know how to use
Functions in Kotlin are super important and they are one of the many vital aspects of the language. One special collection of standard functions is called scope functions which are part of the Kotlin library: let
, run
, also
, apply
and with
.
There’s a big chance you came across those already but maybe you need some guidance on how to choose the right one and how to use them. With this article, I want to demonstrate the differences between all scope functions and discuss relevant use cases. Towards the end of the article there will be an example showing how to apply scope functions in order to structure Kotlin code in a more idiomatic way.
The Importance of Functions
In Kotlin, functions are as important as basic types such as integers or strings. Functions can exist on the same level as classes, may be assigned to variables and can also be passed to/returned from other functions. Kotlin makes functions “first-class citizens” of the language, which Wikipedia describes as follows:
A first-class citizen […] is an entity which supports all the operations generally available to other entities. These operations typically include being passed as an argument, returned from a function, modified, and assigned to a variable.