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

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:

主站蜘蛛池模板: 聊城市| 项城市| 蓬莱市| 马公市| 罗定市| 宁南县| 天等县| 邻水| 四川省| 旺苍县| 邹城市| 景泰县| 桓仁| 柳江县| 邯郸市| 扶沟县| 民勤县| 金门县| 宜兰市| 昌宁县| 铜山县| 天气| 蒲城县| 平顶山市| 廊坊市| 西充县| 腾冲县| 长沙市| 旺苍县| 千阳县| 准格尔旗| 辉县市| 和田市| 灵寿县| 通化市| 宝丰县| 贵定县| 宜春市| 巫溪县| 都匀市| 天长市|