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

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)
}
主站蜘蛛池模板: 蕲春县| 彰化县| 贵溪市| 富阳市| 平陆县| 临沧市| 石台县| 关岭| 垫江县| 通化市| 阳江市| 昌吉市| 景德镇市| 河池市| 元阳县| 定边县| 东海县| 区。| 宜丰县| 成武县| 上杭县| 五华县| 衡阳县| 尤溪县| 左权县| 阳春市| 黄大仙区| 天全县| 崇义县| 兴安盟| 抚松县| 遂宁市| 逊克县| 巧家县| 宁波市| 突泉县| 仙游县| 淮安市| 淮北市| 新乡县| 济源市|