August 2017
Intermediate to advanced
440 pages
10h
English
The classic Java for loop, where we need to define the iterator explicitly, is not present in Kotlin. Here is an example of this kind of loop in Java:
//Java
String str = "Foo Bar";
for(int i=0; i<str.length(); i++)
System.out.println(str.charAt(i));
To iterate through a collection of items from start to finish, we can simply use the for loop instead:
var array = arrayOf(1, 2, 3)
for (item in array) {
print(item)
}
It can also be defined without a block body:
for (item in array)
print(item)
If a collection is a generic collection, then item will be smart cast to a type corresponding to a generic collection type. In other words, if a collection contains elements of type Int, the item will be smart cast to Int:
var array ...
Read now
Unlock full access