- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 375字
- 2021-06-24 14:13:27
Loops
Kotlin supports the usual duo of loop constructs found in most languages—the while loop and the for loop. The syntax for while loops in Kotlin will be familiar to most developers, as it is exactly the same as most C-style languages:
while (true) { println("This will print out for a long time!") }
The Kotlin for loop is used to iterate over any object that defines a function or extension function with the name iterator. All collections provide this function:
val list = listOf(1, 2, 3, 4) for (k in list) { println(k) } val set = setOf(1, 2, 3, 4) for (k in set) { println(k) }
Note the syntax using the in keyword. The in operator is always used with the for loops. In addition to collections, integral ranges are directly supported either inline or defined outside:
val oneToTen = 1..10 for (k in oneToTen) { for (j in 1..5) { println(k * j) } }
Any object can be used inside a for loop provided that it implements a function called iterator , making this an extremely flexible construct. This function must return an instance of an object that provides the following two functions:
- The fun hasNext(): Boolean operator
- The fun next(): T operator
The compiler doesn't insist on any particular interface, as long as the object returned has those two functions present. For example, in the standard String class, Kotlin provides an iterator extension function that adheres to the required contract, and so strings can be used in a for loop to iterate over the individual characters:
val string = "print my characters" for (char in string) { println(char) }
Arrays have an extension function called indices, which can be used to iterate over the index of an array:
for (index in array.indices) { println("Element $index is ${array[index]}") }
- Getting Started with Citrix XenApp? 7.6
- Learning Apex Programming
- R語言數據可視化之美:專業圖表繪制指南
- VMware vSphere 6.7虛擬化架構實戰指南
- Animate CC二維動畫設計與制作(微課版)
- 編寫高質量代碼:改善C程序代碼的125個建議
- Java Web基礎與實例教程
- Python機器學習經典實例
- C#程序設計教程(第3版)
- C專家編程
- Creating Data Stories with Tableau Public
- Getting Started with Polymer
- Python期貨量化交易實戰
- Simulation for Data Science with R
- MongoDB Cookbook(Second Edition)