Become in Kotlin Ranges used to create a continuous sequence of values to represent. Ranges can be used for both numbers and characters. They are useful in various situations, especially when combined with loops to make the code more readable and shorter.

Initialization of an area

There are various options available to initialize areas in Kotlin:

  1. ..-Operator creates a range with the values in an ascending order.
  2. downTo function creates a range with the values in a descending order.
  3. until function creates a range between two values, where the Final value is excluded.
  4. step function is used to define an area with a specific step between the values to create.

..-Operator

The ..-Operator is used to initialize a range between two values, including the start and end values. The values ​​within the range are thereby in an ascending order created. In the following example we create a range of 1 – 10, which contains the values 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10 includes.

Below is an example of a canvas.

downTo function

There is also the possibility of an area in descending order with the help of downTo function to create.

step function

Another special function called step allows you to specify the step by which successive elements are created.

until function

The until function is an additional function designed to exclude the upper bound in a range:

Iterate in areas

To iterate in areas in Kotlin, you can use the already known for loop should be used.

In addition to standard iteration, you can also iterate through a range using steps. This is what you use step function.

In this example, we iterate over a range from 1 to 10, but we only output every other value, i.e. 1, 3, 5, 7 and 9.

in and !in operators

Using special operators in and !in You can check in Kotlin whether elements are present or not present in a range:

  • in: Gives true returns if an object is contained in the range.
  • !in: Gives true returns if an object is not included in the scope.

Leave a Comment

Your e-mail address will not be published. Required fields are marked with * marked