Kotlin Tutorial

Kotlin Classes

Kotlin Ranges

Recently you learned how we can create ranges in Kotlin.

You can create a range by using two dots (..)

				
					var numbers = 1..5
println(numbers)
				
			

The code above outputs:

				
					1..5
				
			

To print all these values from 1 to 5 we should use range in for loop to iterate the range and print the values.

Remember?: In for loop, the example of iterating ranges you learned how we iterate through ranges.

Example:

				
					var numbers = 1..5
for (i in numbers) println(i)
				
			

OR

				
					for (i in 1..5) println(i)
				
			

The code above outputs:

				
					1
2
3
4
5

				
			

There we go.

You also can create ranges in alphabets:

Example

				
					var alphabets = 'a'..'f'
for (i in alphabets) println(i)
				
			

OR

				
					for (i in 'a'..'f') println(i)
				
			

The following code outputs:

				
					a
b
c
d
e
f

				
			

in and !in operators

  • in operator check if the value is in the range
  • !in check if the value is not in the range

Example of in operator:

				
					var numbers = arrayOf(1, 2, 3, 4, 5)

if (2 in numbers) {
   println("2 is here")
} else {
   println("2 is not here")
}

				
			

The code above outputs:

				
					2 is here
				
			

Example of !in operator:

				
					var numbers = arrayOf(1, 2, 3, 4, 5)

if (6 !in numbers) {
   println("6 is not here")
} else {
   println("6 is here")
}

				
			

The code above outputs:

				
					6 is not here
				
			

Break and Continue in Ranges:

				
					var numbers = arrayOf(1, 2, 3, 4, 5)

if (6 !in numbers) {
   println("6 is not here")
} else {
   println("6 is here")
}

				
			

The code above outputs:

				
					1
2

				
			

Example of continue in range:

				
					for (i in 1..6) {
   if (i == 3) {
       continue
   }
   println(i)
}

				
			

The code above outputs:

				
					1
2
4
5
6