In the previous Kotlin tutorial we saw how to define basic variables using var/val and learned about the basic data types that Kotlin provides. Now we will look at how to implement control flow in the language using if, else and when.

If-else

Kotlin supports the basic control flow expressions, if and else. If you have ever programmed before in any kind of language, you already know how to use if-else. Below is a basic example.

But that is not only what Kotlin provides. Kotlin allows you to return a value from the if-else branches! Yes, you read it right, you can return values in if-else, lets see how.

Here you can see that we don’t write grade = “some grade” again and again, we just assign the value returned by the if statement to the variable.

Some points to note when returning values in if-else:

  • There is no need of a return keyword while returning any value, you can simply specify the value that you want to return as is.
  • The if-else must be exhaustive i.e if you are using an if statement to return some value then you must specify an else statement otherwise your program will not compile(it doesn’t matter how many else if conditions you have, there must be a final else block).

When

Kotlin doesn’t have a switch statement, the replacement of it is a when statement which is more powerful compared to switch. Lets use the grade that we got from the above if-else block.

Here you can see that we are matching the value of grade variable with all the possible values. Unlike switch statement there is no need for adding a break keyword, if the control enters a block then only the code in that block will be executed.

Now suppose you want to have the same result for “C” and “D”,  all you have to do is write both the conditions separated with a comma.

Similar to if-else you can also return value with when.

As you can see returning values is very similar to that in if-else. Similar to that in a if-else statement you need to have an exhaustive when block when returning and assigning values so you must provide an else block at the end.

Now you can use implement some fairly good control flow in your Kotlin programs. In the upcoming tutorials we will explore more features about the when statement.

Next Tutorial “Getting Started with Kotlin – Tutorial 3 – Looping” >>

<< Previous Tutorial “Getting Started with Kotlin – Tutorial 1 – Basic Syntax, Variables and Data Types”

Leave a Reply

Your email address will not be published.

five × 3 =