DEV Community

Cover image for Matt's Tidbits #73 - Deciding which Kotlin scope function to use
Matthew Groves
Matthew Groves

Posted on • Originally published at Medium

Matt's Tidbits #73 - Deciding which Kotlin scope function to use

Last week I shared my experience of migrating from RxJava 2 -> 3. This time, I have a quick tidbit and some resources on Kotlin scope functions.

Kotlin has a set of handy functions all with slightly different behavior but designed to help make your code easier to read and maintain:

  • let
  • run
  • with
  • apply
  • also

It can be a little confusing to figure out which of these to use in each situation, but lucky for us, the authors of the Kotlin language have some official recommendations which they have shared on this page:
https://kotlinlang.org/docs/reference/scope-functions.html#function-selection

Additionally, I have found this chart on that page to be especially helpful in figuring out which function to use, as it explains common intended usage scenarios:

Furthermore, this helpful chart from Jose Alcérreca (Android Developer Relations @ Google) that was shared by one of my coworkers pairs some of these concepts with code snippets:
https://medium.com/androiddevelopers/kotlin-standard-functions-cheat-sheet-27f032dd4326

Finally, no discussion of these scoping functions would be complete without mentioning this article by Digital Products' own Anton Spaans:
https://medium.com/the-kotlin-chronicle/lets-also-apply-a-run-with-kotlin-on-our-minds-56f12eaef5e3

I hope you learned some things and feel better equipped to use the Kotlin scoping functions in your own project! Do you have your own ways of remembering which of these functions to apply when? (unintended joke there) - let me know in the comments! And, please follow me on Medium if you're interested in being notified of future tidbits.

This tidbit was originally delivered on June 19, 2020.

Top comments (0)