- Kotlin Programming By Example
- Iyanu Adelekan
- 196字
- 2021-08-27 20:00:11
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)
}
推薦閱讀
- ASP.NET MVC4框架揭秘
- 青少年軟件編程基礎與實戰(圖形化編程三級)
- Java從入門到精通(第4版)
- Implementing Cisco Networking Solutions
- Java虛擬機字節碼:從入門到實戰
- Data Analysis with Stata
- iOS編程基礎:Swift、Xcode和Cocoa入門指南
- QGIS By Example
- Java EE 8 Application Development
- Express Web Application Development
- Python深度學習:模型、方法與實現
- ExtJS Web應用程序開發指南第2版
- 智能手機故障檢測與維修從入門到精通
- Everyday Data Structures
- Python機器學習與量化投資