Kotlin’s Scope Functions by Example
Some of Kotlin’s scope functions can be a bit confusing at first glance. Specifically, apply
, also
, let
, and run
. Even after using them quite a bit, I still need to think about each one’s behavior before adding a new one to my code. I’ve gotten a bit quicker at remembering the correct one but I thought a quick, runnable example would help myself and others visualize the differences. If you’re more of a textual learner, Kotlin’s own site has a table to enumerate each function’s distinctions.
The above example allows us to interactively see what we get with each of the scope functions. I thought about commenting the output of the println
functions but I decided that guessing before running it would be a good exercise left to the reader.