官术网_书友最值得收藏!

The for loop

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 = arrayOf(1, 2, 3) 
 
    for (item in array) 
        print(item) // item is Int 

We can also iterate through the collection using its index:

    for (i in array.indices) 
        print(array[i]) 

The array.indices param returns IntRange with all indexes. It is the equivalent of (1.. array.length - 1). There is also an alternative withIndex library method that returns a list of the IndexedValue property, which contains an index and a value. This can be deconstructed into these elements this way:

    for ((index, value) in array.withIndex()) { 
        println("Element at $index is $value") 
    } 

The construct (index, value) is known as a destructive declaration, and we will discuss it in Chapter 4, Classes and Objects.

主站蜘蛛池模板: 搜索| 延吉市| 东港市| 云龙县| 河东区| 夏河县| 临漳县| 拉萨市| 沙田区| 玛曲县| 吉安县| 阿巴嘎旗| 岳池县| 长丰县| 屏东县| 贵港市| 云霄县| 临城县| 寻乌县| 双牌县| 潼关县| 东乌珠穆沁旗| 黄骅市| 潼南县| 柏乡县| 南溪县| 林西县| 鄄城县| 彝良县| 华亭县| 台前县| 勐海县| 谢通门县| 新竹县| 黄大仙区| 朝阳区| 融水| 望都县| 时尚| 延安市| 罗城|