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