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

Iterating over a list

Collections are used for storing and processing a set of objects. Kotlin provides an elegant syntax for iteration over a collection. 

Consider the code for 9_IteratingOverList.kts:

val names = listOf("Mark", "Tina", "Williams")
for(name in names) {
println(name)
}

 The output is as follows:

If we are interested in getting the index value, we can do that by running the indices command on the collection.

Consider the code for 9a_IteratingOverListIndex.kts:

val names = listOf("Mark", "Tina", "Williams")
for(index in names.indices) {
println(index)
}

The output is as follows:

As the index is a String, we can write an expression to print it. Consider the code for 9b_IteratingOverListIndex.kts:

val names = listOf("Mark", "Tina", "Joseph")
for(index in names.indices) {
println("$index")
}

The output is as follows:

We can also add names to the expression to get items out of the collection, as in the following example, in which we are printing index and name. Consider the code for 9c_IteratingOverList.kts:

val names = listOf("Mark", "Tina", "Joseph")
for(index in names.indices) {
println("$index: ${names.get(index)}")
}

The output is as follows:

主站蜘蛛池模板: 佛冈县| 玉树县| 淄博市| 江西省| 汝城县| 蓬溪县| 青铜峡市| 呼和浩特市| 枝江市| 湘阴县| 济宁市| 乌兰浩特市| 盱眙县| 鹿泉市| 伊金霍洛旗| 盐边县| 新乡县| 五大连池市| 宁强县| 福建省| 奈曼旗| 龙口市| 盐源县| 启东市| 历史| 那坡县| 杭州市| 凯里市| 安宁市| 焉耆| 泾川县| 修水县| 山阳县| 苏州市| 大渡口区| 乌鲁木齐市| 垣曲县| 双辽市| 寿光市| 余姚市| 涟水县|