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

The for loops

The for loop in Kotlin iterates over any object that provides an iterator. It is similar to the for..in loop in Ruby. The loop has this syntax:

for (obj in collection) { … }

The block in the for loop is not necessary if only a single statement exists in the loop. A collection is a type of structure that provides an iterator. Consider the following program:

val numSet = arrayOf(1, 563, 23)

for (number in numSet) {
println(number)
}

Each value in the numSet array is iterated upon by the loop and assigned to the variable number. The number is then printed to the standard system output.

Every element of an array has an index. An index is the position an element holds within an array. The set of indices of an array in Kotlin starts from zero.

If instead of printing the numeric values of the number iterated upon, we wish to print the indices of each number, we can do that as follows:

for (index in numSet.indices) {
println(index)
}

You can specify a type for your iterator variable as well:

for (number: Int in numSet) {
println(number)
}
主站蜘蛛池模板: 鄄城县| 调兵山市| 南漳县| 锡林郭勒盟| 边坝县| 五原县| 奉贤区| 庆元县| 平山县| 莎车县| 昌都县| 唐河县| 宁化县| 梅河口市| 融水| 赣州市| 怀远县| 彭州市| 绥棱县| 犍为县| 桓台县| 怀仁县| 定结县| 大埔区| 滕州市| 剑阁县| 大庆市| 叙永县| 内黄县| 英德市| 阿瓦提县| 龙游县| 永福县| 灵武市| 大丰市| 昭觉县| 师宗县| 巍山| 张家界市| 开阳县| 广河县|