Storing when block subject in a variable

Super short post, on a change introduced in Kotlin 1.3 (yes I know it has been out for a while now). We will take a quick look at capturing the subject of a when block into a scoped variable. This is a quality of life improvement that saves a line or so of code while making the role of the variable clearer.

Below is what you would write before the change:

You can now write this instead:

The instantiation of the enum variable is merged with the declaration of the when block. enum is now scoped to the when block and cannot be accessed outside of it. Not a massive change, but it does makes the code look a little tidier.

Let’s look at one more example:

Becomes:

Not really anything else to say on this subject as there isn’t much to talk about in the first place. You probably get the picture, the example from the Kotlin 1.3 Release Notes might make sense to you if I have failed to explain it myself.

If you found this post helpful, you can follow me on Twitter at @LankyDanDev to keep up with my new posts.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: