Kotlin Tutorial

Kotlin Classes

For Loop:

In Kotlin, the for loop iterates through anything that provides an iterator.

for loop is used to iterate through ranges, arrays, maps (anything that provides an iterator)

Example - Iterating ranges:

				
					fun main(args: Array<String>) {

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

				
			

The code above outputs:

				
					1
2
3
4
5
				
			

Use double dot (..) to create range in Kotlin. In the above example 1..5 means from 1 to 5.

You can omit curly braces if the body contains only one statement like the example above.

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

Example - Iterating array:

				
					var currency = arrayOf("USD", "CSD", "INR", "EURO")

for (i in currency) println(i)
				
			

The code above outputs:

				
					USD
CSD
INR
EURO

				
			

In Kotlin, use arrayOf() to create an array. If you don’t specify the type explicitly the Kotlin compiler is smart enough to judge the array from its values; in the example above the array is of type string Array<String> wanna see the proof? Select the arrayOf and do (Ctrl + Shift + P)  in Windows (Command + Shift + P) in mac.

Example - Iterating array with index:

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

for (i in numbers.indices)
   if (i % 2 == 0)
       println(numbers[i])
				
			

The code above outputs:

				
					0
2
4
6

				
			

Learn more about for loop; visit Kotlin for loop.