Chapter 8. Kotlin Decisions and Loops
We have just learned about variables and we now understand how to change the values that they hold with expressions, but how can we take a course of action that is dependent upon the value of a variable?
We can certainly add the number of new messages to the number of previously unread messages, but how can we, for example, trigger an action within our app when the user has read all their messages?
The first problem is that we need a way to test the value of a variable, and then respond when the value falls within a range of values or is equal to a specific value.
Another problem that is common in programming is that we need sections of our code to be executed a certain number of times (more than once or sometimes not at all) depending on the values of variables.
To solve the first problem, we will look at making decisions in Kotlin with if
, else
, and when
. To solve the latter, we will look at loops in Kotlin with while
, do
– while
, for...