2 min read Β· Updated on by Gabriel Shanahan
Read on to find out about the concept of ranges in Kotlin, the in
operator, and a brief mention of the associated infix functions β until
, downTo
, and step
.
//sampleStart fun main() { for(i in 0..3) { // 1. print(i) } print(" ") for(i in 0 until 3) { // 2. print(i) } print(" ") for(i in 2..8 step 2) { // 3. print(i) } print(" ") for (i in 3 downTo 0) { // 4. print(i) } print(" ") } //sampleEnd
- Iterates over a range starting from 0 up to 3 (inclusive). Like
for (i=0; i<=3; ++i)
in other C-based languages. - Iterates over a range starting from 0 up to 3 (exclusive). Like the
for
loop in Python or likefor(i=0; i< 3; ++i)
in other C-based languages. - Iterates over a range with a custom increment step for consecutive elements.
- Iterates over a range in reverse order
Now, this syntax might seem like itβs awfully ad-hoc, but in time, youβll find out that everything here is actually something you can do yourself, usingΒ operatorsΒ andΒ infix functions. TheΒ ..
Β andΒ in
Β are nothing but syntactic sugar for calls to theΒ rangeToΒ andΒ containsΒ operators, respectively. But all in due time β donβt worry about it for now.
Char
ranges are also supported out of the box:
//sampleStart fun main() { for (c in 'a'..'d') { // 1. print(c) } print(" ") for (c in 'z' downTo 's' step 2) { // 2. print(c) } print(" ") } //sampleEnd
- Iterates over a char range in alphabetical order
- Char ranges support
step
anddownTo
as well
Ranges are also useful in if
statements:
//sampleStart fun main() { val x = 2 if (x in 1..5) { // 1. print("x is in range from 1 to 5") } println() if (x !in 6..10) { // 2. print("x is not in range from 6 to 10") } } //sampleEnd
- Checks if a value is in the range
!in
is the opposite ofin
More info can be found in the docs.