Programming in Kotlin: Fundamentals

Aug 9 2022 · Kotlin 1.6, Android 12, IntelliJ IDEA CE 2022.1.3

Part 2: Manage Control Flow

16. Simplify Code with When Expressions

Episode complete

Play next episode

About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 15. Learn more Loop Features Next episode: 17. Challenge: Use When Expressions

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You learned how if-else expressions are also part of managing the control flow. Sometimes, you have a lot of cases in such an expression, and the logic gets complicated or just too long to cover with just if-else statements. When this happens, you can rely on another statement or expression, the when expression. The when expression is a simplified if, but, at the same time, it's also more powerful. If you've programmed in any other language, you're probably familiar with something called a switch statement. The when is very similar to a switch. When statements have multiple cases, and once any of the cases is met, its block of code or expression executes and then the entire when finishes. Each case in when needs to return a Boolean, or needs to be equal to a value. In that way, it's similar to an if. It's a bit hard to visualize a when without trying it out. Let's see how to implement one. Let's use the when statement to create a basic age classifier. First, declare a constant named age, and assign any age of your choice. Now, if you had to check a person's age, and print out if the person is young, in their teens, twenties, thirties, and so on, that will take a lot of if-else statements, but with the when statements, it's much easier. Start by writing the following code. There are two ways you can implement a when. The first syntax checks if the when's argument value matches a certain value. Within the when, you have to define a set of cases you want to cover. You can then put in fixed values, like so. Here, you're using fixed value matching. In a when, you have to cover all possible cases a value of some type can be, or handle an else case, which covers everything you didn't. Each when case can return a single statement, or return a function block which will execute like in the else case. Run the project and you should see the first case being caught. Now, to create the age classifier, you do range checks from within a when. To do this, update your codes to the following. So, yeah, you can see ranges being utilized instead of fixed values. Run the project and you'll see "in your twenties" is printed out. The important thing is that a when expression requires a Boolean. So, the left-hand side either has to match a value or match a range check. You can also use the when as an expression and have it return the message. Then, you can call the print statement once, instead of calling it in each when case and in the following code below the current when block. This is much concise than a bunch of if-else statements and you only have to call println once. Run the project to see the result is the same. Now, the second way to use a when is without an argument path to the when statement. To start off, add these two constants to your code. You'll be working with an email and password verification when statement to see how powerful a when can be when checking data. No pun intended. (chuckles) Thinking about the data year and the cases, you have to cover five different cases and data to check when an email is empty, email is an invalid format, password is empty, password is too short, and the data is valid. Using if-else statements, this will turn into a lot of code, but, with a when statement, it can be very concise. Start off by creating a when without an argument. When you don't add an argument to a when statement, it requires you to provide an expression in each of the cases for each to evaluate, and an else case for everything else. Start off by adding the first case, which is when an email is empty. Add in the following code. In the first case, you check in the empty case for the email. Enter the following code for the second case, which is the invalid email case. The second case cannot happen unless the first case failed. This means that it can only check to see if the email has an @ symbol only when you pass in an email. Next, add the following cases by pasting them in. In these cases, you use the same approach as with the email. You check to see if the password is empty. Then, in the next case, you check the length. The final case you have to cover is when the data is valid. You can do that in the else case, because, by then, all the validation is done. Enter the following code. This code prints out the data, and notice a plus sign was added in the string. The plus sign here is the concatenation operator, and it is used to join the two strings together. I just used it here to bring the password portion of the string to a new line in the editor. Just a stylistic decision I made here and nothing special. Run the project and check the outputs. The data is valid and you can see the last case printed out. Another thing you can do with a when is to shorten all the expressions or blocks, either only one line of code or one function call. To do this, paste in the following code. Run the project once more and check the output. Using the when statement is awesome, because you can shorten your code and return values to make your code more concise. In the next episode, you'll practice using when statements in a short challenge.