Iterating through collection of items are very common problem in any programming language. But when it comes to latest modern programming languages like Kotlin, this task became more fancy and more options become handy to do different type of iterations. Today we are going to take a deeper look into different version of for loops that could be used in Kotlin Programming Language.
Iterating through Arrays
var language = arrayOf("Ruby", "Koltin", "Python" "Java")
for (item in language){
}
Code language: JavaScript (javascript)
Iterate with For loop
val json = JSONArray(result)
for (i in 0 until json.length()) {
}
Simple For loop
for (i in 1..15) print(i)
Code language: CSS (css)
Decrement For loop
for (i in 15..1) print(i)
for (i in 25 downTo 1) print(i)
Code language: PHP (php)
For loop with step
for (i in 1..5 step 2) print(i)
for (i in 5 downTo 1 step 2) print(i)
Code language: PHP (php)
Foreach like loop with indices
var mystr= "This is Kotlin String"
for (singleChar in mystr.indices) {
/*this will print single character per line*/
println(mystr[singleChar])
}
Code language: JavaScript (javascript)