Reader small image

You're reading from  Android Programming with Kotlin for Beginners

Product typeBook
Published inApr 2019
Reading LevelIntermediate
PublisherPackt
ISBN-139781789615401
Edition1st Edition
Languages
Right arrow
Author (1)
John Horton
John Horton
author image
John Horton

John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.
Read more about John Horton

Right arrow

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, dowhile, for, continue, and break...

Making decisions in Kotlin


Our Kotlin code will constantly be making decisions. For example, we might need to know whether the user has new messages, or whether they have a certain number of friends. We need to be able to test our variables to see whether they meet certain conditions, and then execute a specific section of code depending upon whether they did or not.

In this section, as our code gets more in-depth, it helps to present the code in a way that makes it more readable. Let's take a look at code indenting to make our discussion about making decisions easier.

Indenting code for clarity

You have probably noticed that the Kotlin code in our project is indented. For example, the first line of code inside the MainActivity class is indented by one tab. Additionally, the first line of code is indented inside each function by another tab; here is an annotated diagram to make this clear:

Notice that when the indented block has ended, often with a closing curly brace (}), it is indented to...

Repeating code with loops


Here, we will learn how to repeatedly execute portions of our code in a controlled and precise way by looking at several types of loop in Kotlin. These include while loops, do-while loops, and for loops. We will also learn about the most appropriate situations in which to use these different types of loops.

It is completely reasonable to ask what loops have to do with programming, but they are exactly what the name implies. They are a way of repeating the same part of the code more than once, or looping over the same part of code, although, potentially for a different outcome each time.

This can simply mean doing the same thing until the code being looped over (iterated) prompts the loop to end. It could be a predetermined number of iterations as specified by the loop code itself. It might be until a predetermined situation or condition is met. Or, it could be a combination of these things. Along with if, else, and when, loops are part of the Kotlin control flow...

while loops


Kotlin while loops have the simplest syntax. Think back to the if statements for a moment; we could use virtually any combination of operators and variables in the conditional expression of the if statement. If the expression evaluated to true, then the code in the body of the if block is executed. With the while loop, we also use an expression that can evaluate to true or false:

var x = 10

while(x > 0) {
  Log.i("x=", "$x")
  x--
}

Take a look at the preceding code; what happens here is as follows:

  1. Outside of the while loop, an Int type named x is declared and initialized to 10.

  2. Then, the while loop begins; its condition is x > 0. So, the while loop will execute the code in its body.

  3. The code in its body will repeatedly execute until the condition evaluates to false.

So, the preceding code will execute 10 times.

On the first pass, x equals 10 on the second pass it equals 9, then 8, and so on. But once x is equal to 0, it is, of course, no longer greater than 0. At this point...

do-while loops


The dowhile loop works in the same way as the ordinary while loop except that the presence of a do block guarantees that the code will execute at least once, even when the condition of the while expression does not evaluate to true:

var y = 10
do {
  y++
  Log.i("In the do block and y=","$y")
}
while(y < 10)

If you copy and paste this code into one of your apps in the onCreate function, and then execute it, the output might not be what you expect. Here is the output:

In the do block and y=: 11

This is a less-used but sometimes perfect solution for a problem. Even though the condition of the while loop is false, the do block executes its code, increments the y variable to 11, and prints a message to logcat. The condition of the while loop is y < 10, so the code in the do block is not executed again. If the expression in the while condition is true, however, then the code in the do block continues to execute as though it was a regular while loop.

Ranges


In order to continue our discussion on loops, it is necessary to briefly introduce the topic of ranges. Ranges are intimately connected to the Kotlin topic of arrays, which we will discuss more fully in Chapter 15, Handling Data and Generating Random Numbers. What follows is a quick introduction to ranges to enable us to then go on to cover for loops.

Take a look at the following line of code that uses a range:

val rangeOfNumbers = 1..4 

What is happening is that we are using type inference to create a list of values that contains the values 1, 2, 3, and 4.

We can also explicitly declare and initialize a list, as in the following code:

val rangeOfNumbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

The preceding code uses the listOf keyword to explicitly create a list containing the numbers 1 through to 10 inclusively.

How these work under the hood will be explored in more depth when we learn about arrays in Chapter 15, Handling Data and Generating Random Numbers. Then, we will see that there...

For loops


To use a for loop, we need a range or list. We can then use a for loop to step through that list and execute some code in each step; take a look at the following example:

// We could do this...
// val list = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
// It is much quicker to do this...
val list = 1..10
for (i in list)
  Log.i("Looping through list","Current value is $i")

Take a look at the output this will produce if copied and pasted into an app:

Looping through list: Current value is 1
Looping through list: Current value is 2
Looping through list: Current value is 3
Looping through list: Current value is 4
Looping through list: Current value is 5
Looping through list: Current value is 6
Looping through list: Current value is 7
Looping through list: Current value is 8
Looping through list: Current value is 9
Looping through list: Current value is 10

You can see from the output that the list variable does indeed contain all the values from 1 through to 10. On each pass through the loop...

Controlling loops with break and continue


Having just discussed all the ways that we can control looping through code, it is important to know that sometimes we need to break out of a loop earlier than the condition of the loop specifies.

For such occasions, Kotlin has the break keyword. Here is break in action with a while loop:

var countDown = 10
while(countDown > 0){

  if(countDown == 5)break

  Log.i("countDown =","$countDown")
  countDown --
}

In the preceding code, the condition of the while loop should make the code repeatedly execute while the countDown variable is greater than zero. However, inside the while loop, there is an if expression that checks to see whether countDown is equal to 5. If it is equal to 5, the break statement is used. Also, inside the while loop, the value of countDown is printed to the logcat window and is decremented (reduced by 1). Take a look at the following output when this code is executed:

countDown =: 10
countDown =: 9
countDown =: 8
countDown =:...

Sample code


If you want to play around with loop code, you can create a new project called Loops Demo and copy any of the code from this chapter into the end of the onCreate function. I have placed the code that we have used throughout our discussion of loops in the Chapter08/Loops Demo folder.

Summary


In this chapter, we used if, else, and when to make decisions with expressions and branch our code. We saw and practiced with while, for, and do- while to repeat parts of our code. Furthermore, we used break for breaking out of a loop before the condition would otherwise allow, and we used continue to conditionally execute only part of the code in a loop.

It doesn't matter if you don't remember everything straight away, as we will constantly be using all these techniques and keywords throughout the book. We will also explore a number of more advanced ways to use some of these techniques.

In the next chapter, we will take a much closer look at Kotlin functions, which is where all our tests and loops code will go.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Programming with Kotlin for Beginners
Published in: Apr 2019Publisher: PacktISBN-13: 9781789615401
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at ₹800/month. Cancel anytime

Author (1)

author image
John Horton

John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.
Read more about John Horton