Kotlin - Statement for loop

Introduction

The Kotlin for loop can iterate over any object that defines a function or extension function with the name iterator.

All collections provide this function:

Demo

fun main(args: Array<String>) {

        val list = listOf(1, 2, 3, 4) 
        for (k in list) { 
          println(k) /*w  w  w  . j  a v a2 s.c  om*/
        } 

        val set = setOf(1, 2, 3, 4) 
        for (k in set) { 
          println(k) 
        } 
}

Integral ranges are supported either inline or defined outside:

Demo

fun main(args: Array<String>) {

        val oneToTen = 1..10 
        for (k in oneToTen) { 
          for (j in 1..5) { 
            println(k * j) /*from  w w w .java  2 s . co  m*/
           } 
        } 
}

Any object can be used inside a for loop if it implements a function called iterator.

This function must return an instance of an object that provides the following two functions:

operator fun hasNext(): Boolean 
operator fun next(): T 

The compiler doesn't insist on any particular interface, as long as the object returned has those two functions present.

strings can be used in a for loop to iterate over the individual characters.

Demo

fun main(args: Array<String>) {
        val string = "java2s.com" 
        for (char in string) { 
          println(char) 
        } //  w ww.  j a  v a 2 s  . com
}

Arrays have an extension function called indices, which can be used to iterate over the index of an array.

Demo

fun main(args: Array<String>) {
        val array = arrayOf(1, 2, 3) 
        for (index in array.indices) { 
            println("Element $index is ${array[index]}") 
        } //from  w  ww .ja v a2 s .co m
}