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

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:

主站蜘蛛池模板: 沁源县| 股票| 临泉县| 无为县| 浦城县| 涿州市| 九寨沟县| 南丹县| 砀山县| 逊克县| 武城县| 虹口区| 高安市| 通河县| 涟水县| 永胜县| 若羌县| 尚志市| 宁波市| 沂源县| 永仁县| 怀远县| 沽源县| 怀宁县| 都匀市| 庆元县| 即墨市| 碌曲县| 奇台县| 宜良县| 五河县| 搜索| 南澳县| 昌邑市| 白河县| 中西区| 博罗县| 科尔| 合川市| 丽水市| 枞阳县|