_TL;DR; _Cheat sheet’s at the end of the page.

“I suppose it is tempting, if the only tool you have is a hammer, to treat everything as if it were a nail.”

Formally known as the Golden Hammer rule, American psychologist Abraham Maslow created this simple, yet truthful principle, which devalues over-reliance on a single tool in the process of solving a problem, in favor of a wider array of instruments at someone’s disposal, to tackle an issue with elegance and precision.

JetBrains worked at its finest while developing Kotlin, furnishing developers with dozens of precision Swiss knives, to handle every kind of scenario properly and rigorously.

A bright example of this is the broad set of scope functions offered by the language standard library. Very few languages can show off this whole arsenal of tooling and control over dynamic scoping and object manipulation.

But, in particular, the developer is offered a bunch of different sharp tools for often extremely similar use cases. Whilst being a powerful ally, you need to be responsible and make sure to understand scope functions correctly and use them properly.

There is a lot of documentation and code online regarding this topic. There are however, no official clear-cut guidelines about _which _function is best to pick, depending on the context you’re in. Indeed, the usage of one scope function over another is a little arbitrary, within the range of syntax & semantic correctness. Thus, you have to understand how to make the most out of them and to decide, your coding style for a project, based on your/your team’s preferences.

What‘s a Scope Function to begin with?

We’ll temporarily fly the rigorous definition, and I’ll instead say this: Using scope functions is really just a powerful, clean and compact way of coding. Their ability is to turn repetitive, redundant code into poetry.

Those functions in Kotlin are runlet , apply & also.

They allow you to do magic with objects. You can call a scope function on any object you’d like, because they are both extension functions and generic functions. And since in Kotlin everything is an object, they’re a perfect match.

Another key concept is that sometimes you can do the same thing in more than one way. Of course, runlet , also & apply will all technically do the job for you, since they all solve a similar problem, but in different ways.

Code Example.

Consider the following syntax, which is supposed to create a window and do some trivial operations with it.

val window = ApplicationWindow()

	window.content.loadImage("whatever.png")

	window.header.buttons.add("X")
	window.header.buttons.add("_")
	window.header.buttons.add("□")

	window.onWindowClose = {
	    println("Bye bye")
	}

	window.show()
view raw
scope_functions_sample_1_standard.kt hosted with ❤ by GitHub

What bumps to our eyes in a particular disturbing way is that we have a lot of code which is repeated. Count how many times window appears. We even had to write out window.header.buttons three times.

That’s unbearably redundant and repetitive. Let’s spice this up with scope functions.

val window = ApplicationWindow()
	// 'this' is the global scope
	window.apply {
	    // 'this' scopes to 'window'
	    this.content.loadImage("whatever.png")

	    // 'this' scopes to 'window'
	    this.header.buttons.run {
	        // 'this' scopes to 'window.header.buttons'
	        add("X")
	        add("_")
	        add("□")
	    }

	    // 'this' scopes to 'window'
	    this.onWindowClose = {
	        println("Bye bye")
	    }

	    // 'this' scopes to 'window'
	    this.show()
	}
view raw
scoped_functions_1_scoped-ish.kt hosted with ❤ by GitHub

That’s a big improvement. We can now start to see the impact of scope functions: thanks to our apply block, this points to a different scope. We now have a main editing block to apply changes inside the window object. We also used run in order to cycle the add function three times (We used run instead of apply because we didn’t care about the result).

#coding #function #cheatsheet #kotlin #development

Kotlin Scope Functions: The God-Sent Guide.
1.10 GEEK