Regardless of the programming language used, application development is largely an exercise in applying logic, and much of the art of programming involves writing code that makes decisions based on one or more criteria. Such decisions define which code gets executed, how many times it is executed and, conversely, which code gets by-passed when the program is executing. This is often referred to as flow control since it controls the flow of program execution. Flow control typically falls into the categories of looping control (how often code is executed) and conditional flow control (whether or not code is executed). This chapter is intended to provide an introductory overview of both types of flow control in Kotlin.
You're reading from Android Studio 4.2 Development Essentials - Kotlin Edition
This chapter will begin by looking at flow control in the form of loops. Loops are essentially sequences of Kotlin statements which are to be executed repeatedly until a specified condition is met. The first looping statement we will explore is the for loop.
14.1.1 The Kotlin for-in Statement
The for-in loop is used to iterate over a sequence of items contained in a collection or number range.
The syntax of the for-in loop is as follows:
for variable name in collection or range {
// code to be executed
}
In this syntax, variable name is the name to be used for a variable that will contain the current item from the collection or range through which the loop is iterating. The code in the body of the loop will typically use this name as a reference to the current item in the loop cycle. The collection or range references the item through which the loop is iterating. This could, for example...
In the previous chapter we looked at how to use logical expressions in Kotlin to determine whether something is true or false. Since programming is largely an exercise in applying logic, much of the art of programming involves writing code that makes decisions based on one or more criteria. Such decisions define which code gets executed and, conversely, which code gets by-passed when the program is executing.
14.2.1 Using the if Expressions
The if expression is perhaps the most basic of flow control options available to the Kotlin programmer. Programmers who are familiar with C, Swift, C++ or Java will immediately be comfortable using Kotlin if statements, although there are some subtle differences.
The basic syntax of the Kotlin if expression is as follows:
if (boolean expression) {
// Kotlin code to be performed when expression evaluates to true
}
Unlike some other programming languages, it is important...
The term flow control is used to describe the logic that dictates the execution path that is taken through the source code of an application as it runs. This chapter has looked at the two types of flow control provided by Kotlin (looping and conditional) and explored the various Kotlin constructs that are available to implement both forms of flow control logic.