Home » Kotlin Integer Ranges

Kotlin Integer Ranges

by Online Tutorials Library

Kotlin Ranges

Kotlin range is defined as an interval from start value to the end value. Range expressions are created with operator (. .) which is complemented by in and !in. The value which is equal or greater than start value and smaller or equal to end value comes inside the defined range.

While evaluating the above code val aToZ = ‘a’..’z’as ‘a’in aToZ returns true, ‘b’ in aToZ returns true and so on. The code val oneToNine = 1..9 evaluates as 1 in oneToNine returns true, but the evaluation 10 in oneToNine returns false.

Integral Type Ranges

Integral type ranges (IntRange, LongRange, CharRange) are the ability to use in for loop. The compiler converts this integral type in simple analogue of Java’s index for-loop.

Example of Kotlin range

Output:

12345  abcdef  1.0..5.0  3.14 in range is true  

What happened when we try to iterate a r range in decreasing order using . . operator ? This will print nothing.

   for (a in 5..1){          print(a )// print nothing      }  

To iterate the element in decreasing order, use the standard library downTo() function or downTo keyword.

until range

The until() function or until keyword in range is used to exclude the last element. It iterates range from start to 1 less than end.

The above range excludes 5 and iterate from 1 to 4.

Kotlin range of integer

Let’s see an example of integer range using downTo(), downTo, and rangeTo() methods.

Output:

12345  54321  12345  54321  

Kotlin range of characters

Example of Kotlin ranges using char data types.

Output:

a bcde  edcba  

Kotlin range step

Kotlin step keyword in range is used to iterate the range in the interval of given step value (int value).

Output:

1 3 5 7 9   10 7 4 1  

Kotlin range iterator

An iterator() method is also be used to iterate the range value. It uses hasNext() method which checks the next element in the range and next() method returns the next element of the range.

Output:

a b c d e  

You may also like