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

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:

主站蜘蛛池模板: 壤塘县| 应城市| 寿光市| 姚安县| 邵阳县| 曲麻莱县| 沈丘县| 三穗县| 吉木乃县| 内黄县| 资源县| 两当县| 小金县| 洪泽县| 三江| 蒲城县| 玉林市| 文山县| 南丹县| 周至县| 石狮市| 托里县| 凉山| 乳山市| 新野县| 华容县| 土默特右旗| 新竹县| 新田县| 贵定县| 阿拉尔市| 米脂县| 灯塔市| 古浪县| 延川县| 太仆寺旗| 繁昌县| 乌恰县| 甘肃省| 隆回县| 贡山|