[Kotlin pearls 1] Scope Functions

A diagram to help you to choose the right one!

Do we really need yet another blog post on Kotlin scope functions?

As a matter of fact I think we do. While there are many posts to describe them, I found none on how to pick up the correct function and when you should consider to refactor your code into using one of them.

I’ve tried to make it clear with a diagram:

Use this means we are going to (mostly) call methods on a single object, the reference to the object is this .

Pass it means we need to pass the object to other methods/functions, the reference to the object is it .

Result means we will have a result value from the block and we need to return it.

Side-effects means we don’t expect a result but we want to call for some methods that return Unit (a.k.a. void) and maybe combine them in Fluent Interface style.

So if you are wondering how to simplify some code where an object (the target object) is used multiple times, you should ask yourself two questions: