avatarGabriel Shanahan

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2634

Abstract

syntax_tree">AST</a>, as can be seen in <code>String abc = “abc”, yes = “yes”;</code></p></blockquote><blockquote id="528e"><p><b>Reader:</b> rage-quits</p></blockquote><blockquote id="b23c"><p>….so we’re purposefully avoiding that definition.</p></blockquote><ul><li><b>Statements are everything else.</b></li></ul><p id="9a5c">So, for instance, in Java, <code>if/else</code> is a statement, because you can’t write <code>f(if(true) { ... } else { ... })</code> — this wouldn’t compile. However, <code>4</code> and <code>f(3).add(5)</code> are both expressions, and in Kotlin, it’s legal to use an <code>if</code> as an expression as well (more about this <a href="https://readmedium.com/conditional-expression-7fb52a02b767">later</a>).</p><h1 id="3a70">When, used as a statement</h1> <figure id="3d0a"> <div> <div> <img class="ratio" src="http://placehold.it/16x9"> <iframe class="" src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2F84JsztD2P%3Ffrom%3D1%26to%3D20&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2F84JsztD2P%3Ffrom%3D1%26to%3D20&amp;image=https%3A%2F%2Fplay.kotlinlang.org%2Fassets%2Fog-image.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" allowfullscreen="" frameborder="0" height="300" width="800"> </div> </div> </figure></iframe></div></div></figure><ol><li>This is a <code>when</code> statement</li><li>Checks whether <code>obj</code> equals <code>1</code></li><li>Checks whether <code>obj</code> equals<code>Hello</code></li><li>Performs type checking. The right hand side can be a block of code, delimited by <code>{</code> and <code>}</code>. Notice how <code>obj</code> is automatically cast to <code>Long</code>. This feature is called <a href="https://kotlinlang.org/docs/typecasts.html#smart-casts">smart casting</a>, and we’ll talk about it more in the article about <a href="https://readmedium.com/types-142c319e5923">Types</a>.</li><li>Performs inverse type checking</li><li>Default branch. This might be omitted in certain situations (the above code is one of them), and required in others. These situations will become clear in time, don’t worry about them for now. The compiler will let you know if the branch is missing and you need to include it.</li></ol><p id="a73c">Note that all branch conditions are checked sequentially until one that is satisfied is found. So, only the first suitable branch will be executed.</p><h1 id="8949">When, used as an expression</h1> <figure id="7b2f"> <d

Options

iv> <div> <img class="ratio" src="http://placehold.it/16x9"> <iframe class="" src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2FfUy3bSqeF%3Ffrom%3D1%26to%3D20&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2FfUy3bSqeF%3Ffrom%3D1%26to%3D20&amp;image=https%3A%2F%2Fplay.kotlinlang.org%2Fassets%2Fog-image.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" allowfullscreen="" frameborder="0" height="300" width="800"> </div> </div> </figure></iframe></div></div></figure><ol><li>This is a <code>when</code> expression. It must <b>always</b> evaluate to a specific value (try omitting the <code>else</code> branch and see what happens)</li><li>Sets the value of <code>result</code> to <code>"one"</code> if <code>obj</code> equals to one.</li><li>Sets the value of <code>result</code> to <code>1</code> if <code>obj</code> equals to <code>Hello</code>.</li><li>Sets the value to <code>obj > 5</code> if <code>obj</code> is an instance of <code>Long</code>. Notice how, as before, you can use code blocks — the last expression in a code block is taken to be the value of the entire code block (and this is true generally, not only in <code>when</code> expressions). Also notice how, as before, <code>obj</code> gets smart-casted to <code>Long</code>.</li><li>Sets the value “42” if none of the previous conditions are satisfied. Unlike in a <code>when</code> <i>statement</i>, the default branch is usually required in a <code>when</code> <i>expression</i>, except for case where the compiler can verify that the branches already cover all possible cases (more on this when we cover <a href="https://readmedium.com/sealed-hierarchies-introduction-692969ef9c6f">Sealed Classes</a>).</li></ol><p id="6ca4">More can be found in <a href="https://kotlinlang.org/docs/control-flow.html#when-expression">the docs</a>.</p><p id="b7a1">Go back to <a href="https://readmedium.com/basic-variables-198578c0a2d4">Basic Variables</a>, jump to the <a href="https://readmedium.com/table-of-contents-c52573cfa291">Table of Contents</a>, or continue to <a href="https://readmedium.com/loops-1d2b5ad83899">Loops</a>.</p><figure id="8ecd"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*biBSB579iezsNvEQ_NMLBg.png"><figcaption><a href="https://www.etnetera.cz/prace-u-nas?utm_source=medium&amp;utm_medium=GabrielShanahan&amp;utm_campaign=KotlinPrimer&amp;utm_content=join-our-team&amp;utm_term=KotlinPrimer#pozice">Join me in Etnetera</a></figcaption></figure></article></body>

When Construct

Demonstrating the when construct, with a quick note on smart casting and expressions vs. statements.

— — — — — — — — — — — — — — —

THE CURRENT VERSION OF THIS ARTICLE IS PUBLISHED HERE.

— — — — — — — — — — — — — — —

Tags: #KOTLIN FEATURE

This article is part of the Kotlin Primer, an opinionated guide to the Kotlin language, which is indented to help facilitate Kotlin adoption inside Java-centric organizations. It was originally written as an organizational learning resource for Etnetera a.s. and I would like to express my sincere gratitude for their support.

It is recommended to read the Introduction before moving on. Check out the Table of Contents for all articles.

Instead of the widely used switch statement, Kotlin provides the more flexible and clear when construct. It can be used both as a statement and as an expression.

Expressions vs. Statements

What is and isn’t an expression/statement depends on the language.

A simple way of understanding the difference between expressions and statements is this:

  • Expressions in a given language are anything that you can legally use as an argument to a function.

Intuitively, this seems to be the same as saying “anything that can be on the right hand side of an assignment”, but things get funky when semicolons get involved — 3 is an expression, 3; is a statement.

Reader: “But in Java, Integer a = 3; is legal!”

Author: “But that’s because the ; is not actually part of the assignment in the AST, as can be seen in String abc = “abc”, yes = “yes”;

Reader: *rage-quits*

….so we’re purposefully avoiding that definition.

  • Statements are everything else.

So, for instance, in Java, if/else is a statement, because you can’t write f(if(true) { ... } else { ... }) — this wouldn’t compile. However, 4 and f(3).add(5) are both expressions, and in Kotlin, it’s legal to use an if as an expression as well (more about this later).

When, used as a statement

  1. This is a when statement
  2. Checks whether obj equals 1
  3. Checks whether obj equalsHello
  4. Performs type checking. The right hand side can be a block of code, delimited by { and }. Notice how obj is automatically cast to Long. This feature is called smart casting, and we’ll talk about it more in the article about Types.
  5. Performs inverse type checking
  6. Default branch. This might be omitted in certain situations (the above code is one of them), and required in others. These situations will become clear in time, don’t worry about them for now. The compiler will let you know if the branch is missing and you need to include it.

Note that all branch conditions are checked sequentially until one that is satisfied is found. So, only the first suitable branch will be executed.

When, used as an expression

  1. This is a when expression. It must always evaluate to a specific value (try omitting the else branch and see what happens)
  2. Sets the value of result to "one" if obj equals to one.
  3. Sets the value of result to 1 if obj equals to Hello.
  4. Sets the value to obj > 5 if obj is an instance of Long. Notice how, as before, you can use code blocks — the last expression in a code block is taken to be the value of the entire code block (and this is true generally, not only in when expressions). Also notice how, as before, obj gets smart-casted to Long.
  5. Sets the value “42” if none of the previous conditions are satisfied. Unlike in a when statement, the default branch is usually required in a when expression, except for case where the compiler can verify that the branches already cover all possible cases (more on this when we cover Sealed Classes).

More can be found in the docs.

Go back to Basic Variables, jump to the Table of Contents, or continue to Loops.

Join me in Etnetera
Kotlin
Java
Programming
When
Learning
Recommended from ReadMedium