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

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:

主站蜘蛛池模板: 延津县| 梧州市| 定兴县| 洛扎县| 古交市| 壤塘县| 多伦县| 洪泽县| 上蔡县| 蒙阴县| 鱼台县| 颍上县| 泰宁县| 北流市| 南澳县| 蓬莱市| 安远县| 塘沽区| 康保县| 江城| 海淀区| 泗阳县| 龙胜| 马山县| 富平县| 喜德县| 同江市| 抚宁县| 云霄县| 望谟县| 松阳县| 崇信县| 梁山县| 临武县| 澳门| 区。| 宁南县| 大田县| 济宁市| 香格里拉县| 余江县|