{"id":3114,"date":"2020-01-28T10:04:27","date_gmt":"2020-01-28T15:04:27","guid":{"rendered":"http:\/\/bluegalaxy.info\/codewalk\/?p=3114"},"modified":"2020-01-28T10:04:29","modified_gmt":"2020-01-28T15:04:29","slug":"kotlin-how-to-use-the-when-expression","status":"publish","type":"post","link":"https:\/\/bluegalaxy.info\/codewalk\/2020\/01\/28\/kotlin-how-to-use-the-when-expression\/","title":{"rendered":"Kotlin: How to use the &#8216;when&#8217; expression"},"content":{"rendered":"\n<p>In addition to <code>if<\/code>, <code>for<\/code>, and <code>while<\/code> loops, Kotlin also has a control flow option called <code>when<\/code>. The &#8216;when&#8217; expression acts just like a switch operator you might see in other languages. The basic structure looks like this:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">when (variableToBeExamined) {\n    1 -> print(\"variableToBeExamined is set to 1\")\n    2 -> print(\"variableToBeExamined is set to 2\")\n    else -> { \/\/ Note the curly braces\n        print(\"variableToBeExamined contains neither 1 nor 2\")\n    }\n}<\/pre>\n\n\n\n<p>Some notes about this switch structure:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The first line uses the key word <code>when<\/code> followed by a variable name in parenthesis<\/li><li>The entire &#8216;when&#8217; structure is wrapped in curly braces<\/li><li>The values that we want to set switch cases on go on the left, followed by an arrow operator <code>-><\/code> and then what we want to have happen for each condition goes on the right side<\/li><li>We can use an <code>else<\/code> block at the end of the <code>when<\/code> structure, but it requires its own set of curly braces! (when the <code>when<\/code> structure is used as an expression)<\/li><\/ul>\n\n\n\n<p>Here is what <a href=\"https:\/\/kotlinlang.org\/docs\/reference\/control-flow.html\">kotlinlang.org<\/a> docs say about <code>when<\/code>:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p><em>when<\/em> matches its argument against all branches sequentially until some branch condition is satisfied. <em>when<\/em> can be used either as an expression or as a statement. If it is used as an expression, the value of the satisfied branch becomes the value of the overall expression. If it is used as a statement, the values of individual branches are ignored. (Just like with <em>if<\/em>, each branch can be a block, and its value is the value of the last expression in the block.)<\/p><p>The <em>else<\/em> branch is evaluated if none of the other branch conditions are satisfied. If <em>when<\/em> is used as an expression, the <em>else<\/em> branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions (as, for example, with <a href=\"https:\/\/kotlinlang.org\/docs\/reference\/enum-classes.html\"><em>enum<\/em> class<\/a> entries and <a href=\"https:\/\/kotlinlang.org\/docs\/reference\/sealed-classes.html\"><em>sealed<\/em> class<\/a> subtypes).<\/p><\/blockquote>\n\n\n\n<p>It is also possible to combine values on the left, separated by a comma. For example:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">when (x) {\n    0, 1, 2, 3, 4 -> print(\"x is between 0 and 4\")\n    else -> print(\"x is not a value between 0 and 4\")\n}<\/pre>\n\n\n\n<p>Another way to do the same thing as above, but using ranges (with the <code>in<\/code> <code>..<\/code> notation):<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">when (x) {\n    in 0..4 -> print(\"x is in the range\")\n    in validNumbers -> print(\"x is valid\")\n    in 5..20 -> print(\"x is outside the range\")\n    else -> print(\"none of the above\")\n}<\/pre>\n\n\n\n<p>In addition to using <code>when<\/code> as a switch statement or expression, it can also be used as a replacement for an <code>if-else if<\/code> chain. In this case, there are no parenthesis after the &#8216;when&#8217;. For example:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">when {\n    x.isOdd() -> print(\"x is odd\")\n    x.isEven() -> print(\"x is even\")\n    else -> print(\"x is not a number\")\n}<\/pre>\n\n\n\n<p>One more example of what can be done with <code>when<\/code>. Inside the &#8216;when&#8217; parenthesis, it is possible to set a variable that is based on a function call, and then use that variable in the body of the &#8216;when&#8217; structure. For example:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">fun Request.getBody() =\n        when (val response = executeRequest()) {\n            is Success -> response.body\n            is HttpError -> throw HttpException(response.status)\n        }<\/pre>\n\n\n\n<p><br>For more information about Kotlin control flow options, including the <code>when<\/code> structure, see:<br><a href=\"https:\/\/kotlinlang.org\/docs\/reference\/control-flow.html\">https:\/\/kotlinlang.org\/docs\/reference\/control-flow.html<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In addition to if, for, and while loops, Kotlin also has a control flow option called when. The &#8216;when&#8217; expression acts just like a switch operator you might see in other languages. The basic structure looks like this: Some notes about this switch structure: The first line uses the key word when followed by a &hellip; <a href=\"https:\/\/bluegalaxy.info\/codewalk\/2020\/01\/28\/kotlin-how-to-use-the-when-expression\/\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Kotlin: How to use the &#8216;when&#8217; expression<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[214],"tags":[215],"class_list":["post-3114","post","type-post","status-publish","format-standard","hentry","category-kotlin","tag-kotlin"],"_links":{"self":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts\/3114","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/comments?post=3114"}],"version-history":[{"count":10,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts\/3114\/revisions"}],"predecessor-version":[{"id":3124,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts\/3114\/revisions\/3124"}],"wp:attachment":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/media?parent=3114"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/categories?post=3114"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/tags?post=3114"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}