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

Next
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.

Transcript: 16. Simplify Code with When Expressions

You learned how If/Else expressions are also a 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/expression: The when expressions!

A 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. A when is very similar to a switch.

When statements can 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.

val age = 23

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 would take a lot of if/else statements.

But with a when statement, it’s much easier. Start by writing the following code:

when(age) {

}

There’re two ways you can implement a when. The first syntax checks if 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:

when(age) {
 23 -> println("Close to a quarter century!")
 25 -> println("Quarter century!")
 else -> {
   println("Don't know your age!")
 }
}

Here, you’re using fixed value matching. In a when, you have to cover all the 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 code to the following:

when(age) {
  in 0..12 -> println("Still a young human")
  in 13..19 -> println("Teenager")
  in 20..29 -> println("In your twenties")
  in 30..39 -> println("In your thirties")
  in 40..49 -> println("In your forties")
  else -> println("You're a wise person :]")
}

So here 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.

Add in the following code below the current when block:

val message = when(age) {
  in 0..12 -> "Still a young human"
  in 13..19 -> "Teenager"
  in 20..29 -> "In your twenties"
  in 30..39 -> "In your thirties"
  in 40..49 -> "In your forties"
  else -> "You're a wise person :]"
}

println(message)

This is much more 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 passed to the when statement. To start off, add these two constants to your code:

val email = "mail@mail.com"
val password = "iLoveKotlin!"

You’ll be working on an email & password verification when statement, to see how powerful a when can be when checking data. No pun intended.

Thinking about the data here and the cases, you have to cover five different cases. And they are to check when an:

  • Email is empty
  • Email is in invalid format
  • Password is empty
  • Password is too short and
  • The data is valid

Using if/else statements, this would 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 {
}

When you don’t add an argument to a when statement, it requires you to provide an expression in each of the cases for it 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:

when {
  email.isEmpty() -> {
    println("You need to choose an email!")
  }
}

In the first case, you are checking the empty case for the email.

Enter the following code for second case which is the invalid email case:

when {
  ...
  
  "@" !in email -> {
    println("Your email is invalid :[")
  }
}

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:

when {
  ...
  
  password.isEmpty() -> {
    println("You need to choose a password!")
  }

  password.length < 10 -> {
    println("Password not strong enough :[")
  }
}

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 the 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:

when {
  ...
  
  else -> {
   println("Email length: ${email.length}, " +
      "Password length: ${password.length}")
  }
}

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 string 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 output.

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 if they are only one line of code or one function call.

To do this, paste in the following code:

when {
  email.isEmpty() -> println("You need to choose an email!")

  "@" !in email -> println("Your email is invalid :[")

  password.isEmpty() -> println("You need to choose a password!")

  password.length < 10 -> println("Password not strong enough :[")

  else -> println("Email length: ${email.length}, " +
  "Password length: ${password.length}")
}

Run the project once more, and check the output.

Using a 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!