- Android Development with Kotlin
- Marcin Moskala Igor Wojda
- 241字
- 2021-07-02 18:48:38
The for loop
The classic Java for loop, where we need to define the iterator explicitly, is not present in Kotlin. Here is an example of this kind of loop in Java:
//Java String str = "Foo Bar"; for(int i=0; i<str.length(); i++) System.out.println(str.charAt(i));
To iterate through a collection of items from start to finish, we can simply use the for loop instead:
var array = arrayOf(1, 2, 3) for (item in array) { print(item) }
It can also be defined without a block body:
for (item in array) print(item)
If a collection is a generic collection, then item will be smart cast to a type corresponding to a generic collection type. In other words, if a collection contains elements of type Int, the item will be smart cast to Int:
var array = arrayOf(1, 2, 3) for (item in array) print(item) // item is Int
We can also iterate through the collection using its index:
for (i in array.indices) print(array[i])
The array.indices param returns IntRange with all indexes. It is the equivalent of (1.. array.length - 1). There is also an alternative withIndex library method that returns a list of the IndexedValue property, which contains an index and a value. This can be deconstructed into these elements this way:
for ((index, value) in array.withIndex()) { println("Element at $index is $value") }
The construct (index, value) is known as a destructive declaration, and we will discuss it in Chapter 4, Classes and Objects.
- Spring 5企業級開發實戰
- JavaScript+jQuery網頁特效設計任務驅動教程(第2版)
- Linux核心技術從小白到大牛
- Vue.js入門與商城開發實戰
- Java FX應用開發教程
- Web Application Development with R Using Shiny(Second Edition)
- 人人都是網站分析師:從分析師的視角理解網站和解讀數據
- PhoneGap Mobile Application Development Cookbook
- Functional Kotlin
- HTML5與CSS3基礎教程(第8版)
- Mastering C++ Multithreading
- Julia for Data Science
- 深入實踐Kotlin元編程
- Java圖像處理:基于OpenCV與JVM
- 區塊鏈架構之美:從比特幣、以太坊、超級賬本看區塊鏈架構設計