Defining the for loop 

The following points are necessary to create a for loop:

  • Declare a range with a start and end point. Ranges are defined with two dots, .., for example, var range = 1..3
  • With a for loop, create a variable and assign a range with in operator. 
  • Define a code block that will execute a task:
fun main(args: Array<String>) {
var range = 1..3
for (i in range) {
println("value of $i")
}
}

On the first iteration, the for loop initializes the i variable with the first value of the range, and on each iteration the next value from the range will be assigned to i

Any object that has an iterator function implemented can be used inside a for loop, for example, range, list, array, and so on.

With each iteration, the for loop assigns the next member from the range, which can be utilized as a normal member variable. In this example, each value from the range is printed on the screen:

fun main(args: Array<String>) {
val list = listOf(1,2,3,4)
for (l in list){
println("value of $l")
}

val message = "kotlin is awesome"
for (m in message){
println(m)
}
}

The for loop with ranges and iterator will be discussed in Chapter 5, Data Collection, Iterators, and Filters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.77.153