- Hands-On Design Patterns with Kotlin
- Alexey Soshin
- 231字
- 2021-06-25 20:49:25
The for loop
The for loop in Java, which prints each character of a string on a new line, may look something like this:
final String word = "Word";
for (int i = 0; i < word.length; i++) {
}
The same loop in Kotlin is:
val word = "Word";
for (i in 0..(word.length-1)) {
println(word[i])
}
Note that while the usual for loop in Java is exclusive (it excludes the last index by definition, unless specified otherwise), the for loop over ranges in Kotlin is inclusive. That's the reason we have to subtract one from the length to prevent overflow (string index out of range): (word.length-1).
If you want to avoid that, you can use the until function:
val word = "Word";
for (i in 0 until word.length) {
println(word[i])
}
Unlike some other languages, reversing the range indexes won't work:
val word = "Word";
for (i in (word.length-1)..0) {
println(word[i])
} // Doesn't print anything
If your intention is to print the word in reverse order, for example, use the downTo function:
val word = "Word";
for (i in (word.length-1) downTo 0) {
println(word[i])
}
It will print the following output:
d
r
o
W
It may seem confusing that until and downTo are called functions, although they look more like operators. This is another interesting Kotlin feature called infix call, which will be discussed later on.
- Learning Scala Programming
- 深度實踐OpenStack:基于Python的OpenStack組件開發
- Mastering OpenCV Android Application Programming
- C語言最佳實踐
- Java:Data Science Made Easy
- jQuery從入門到精通 (軟件開發視頻大講堂)
- Magento 1.8 Development Cookbook
- Python程序設計與算法基礎教程(第2版)(微課版)
- CRYENGINE Game Development Blueprints
- R Data Science Essentials
- Data Science Algorithms in a Week
- 分布式架構原理與實踐
- Advanced Python Programming
- 你真的會寫代碼嗎
- SQL Server 2012 數據庫應用教程(第3版)